LeetCode 43 字符串相乘

思路

用一个数组记录乘积的结果,最后处理进位。

代码

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1 == "0" || num2 == "0")  return "0";
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        int a[num1.length() + num2.length() + 1] = {0};
        for(int i = 0; i < num1.length(); i++){
            for(int j = 0; j < num2.length(); j++){
                a[i + j] += (num1[i] - '0') * (num2[j] - '0');
            }
        }
        int mod = 0;
        for(int i = 0; i <= num1.length() + num2.length(); i++){
            a[i] += mod;
            mod = a[i] / 10;
            a[i] %= 10;
        }
        int i = num1.length() + num2.length();
        while(!a[i])    i--;
        string ans = "";
        while(i >= 0){
            ans += a[i] + '0';
            i--;
        }
        return ans;
    }
};
posted @ 2020-02-28 15:25  阳离子  阅读(109)  评论(0编辑  收藏  举报