【LeetCode】43. Multiply Strings

来源:互联网 发布:备案的是域名还是主机 编辑:程序博客网 时间:2024/06/06 19:36

题目描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题思路

大数相乘。
为了解题思路清晰,我是自己模拟手工相乘的方法做的。具体见代码注释。

AC代码

class Solution {public:    //给数组左边加0,使其最终长度为tLen    string leftPad(string num, int tLen) {        int numLen = num.size();        string zero(tLen - numLen, '0');        return zero + num;    }    //大数相加。先将两个大数前面补0使其长度相同,注意最后的carry    string strAdd(string num1, string num2) {        int maxLen = max(num1.size(), num2.size());        num1 = leftPad(num1, maxLen);        num2 = leftPad(num2, maxLen);        string ans;        int carry = 0;        for (int idx = maxLen - 1; idx >= 0; --idx) {            int curSum = (num1[idx] - '0') + (num2[idx] - '0');            curSum += carry;            ans.push_back((curSum % 10) + '0');            carry = curSum / 10;        }        if (carry != 0)            ans.push_back(carry + '0');        reverse(ans.begin(), ans.end());        return ans;    }    //大数相乘。每次使用一个位与另一个数字相乘,然后通过大数相加更新答案。    string multiply(string num1, string num2) {        if (num2 == "0" || num1 == "0")            return "0";        string ans;        for (int i = num2.size() - 1; i >= 0; --i) {            if (num2[i] == '0')                continue;            string curAns;            int carry = 0;            for (int j = num1.size() - 1; j >= 0; --j) {                int mul = (num2[i] - '0') * (num1[j] - '0');                mul += carry;                curAns.push_back((mul % 10) + '0');                carry = mul / 10;            }            if (carry != 0)                curAns.push_back(carry + '0');            reverse(curAns.begin(), curAns.end());            string zeros(num2.size() - i - 1, '0');            ans = strAdd(ans, curAns + zeros);        }        return ans;    }};
0 0
原创粉丝点击