LeetCode第 43 题:字符串相乘(C++)

43. 字符串相乘 - 力扣(LeetCode)

参考题解:高频面试系列:字符串乘法 - 字符串相乘 - 力扣(LeetCode)

题目并不难,算是加法运算的进阶,记得处理进位就行,可以看上面那个兄弟画的图。

反正就是多画图,多画图帮助思考。

class Solution {
public:
    string multiply(string num1, string num2) {
        int m = num1.size(), n = num2.size();
        vector<int> res(m+n, 0);//显然相乘的位数最多就是m+n
        for(int i = m-1; i >= 0; --i){//从各位开始
            for(int j = n-1; j >= 0; --j){
                int mul = (num1[i] - '0') * (num2[j] - '0');
                int x = (mul + res[i+j+1])/10;//记录进位
                res[i+j+1] =  (mul + res[i+j+1]) % 10;
                res[i+j] += x;//注意这儿是"+="
            }
        }
        int i = 0;
        while(i < res.size() && res[i] == 0)    ++i;
        string str;
        for(; i < res.size(); ++i)  str += '0'+res[i];
        return str.size() == 0 ? "0" : str;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/107850851