LeetCode每天刷day29:Multiply Strings

版权声明:本文为博主原创文章,未经博主允许可以转载。(转呀转呀/笑哭),希望标注出处hhh https://blog.csdn.net/qq_36428171/article/details/89290453

题目:
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

题目链接:Multiply Strings

C++:

class Solution {
public:
string multiply(string num1, string num2) {
        if (num1[0] == '0' || num2[0] == '0')
            return "0";
        int len1 = num1.size(), len2 = num2.size();
        int num[len1 + len2] = {0};
        for (int i = num1.size() - 1; i >= 0; i--) 
            for (int j = num2.size() - 1; j >= 0; j--)
                num[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
        
        int carry = 0;
        for (int i = len1 + len2 - 1; i >= 0; i--) {
            num[i] += carry;
            carry = num[i] / 10;
            num[i] %= 10;
        }
        string ans;
        int idx = 0;
        while (idx < len1 + len2 && num[idx] == 0)
            idx++;
        for (; idx < len1 + len2; idx++)
            ans += num[idx] + '0';
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36428171/article/details/89290453