Leetcode 43. Multiply Strings (大数乘法好题)

  1. Multiply Strings
    Medium
    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Example 1:

Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:

Input: num1 = “123”, num2 = “456”
Output: “56088”

Constraints:

1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.

解法1:参考的labuladong的做法。
https://labuladong.github.io/algo/di-san-zha-24031/jing-dian–a94a0/zi-fu-chua-07daa/
num1[i] 和 num2[j] 的乘积对应的就是 nums[i+j] 和 nums[i+j+1] 这两个位置!
注意下面3行代码很关键! nums[i+j] 和 nums[i+j+1]都是在sum的基础上,一个是sum要%10,一个要把sum/10,然后把carry加上去!

                int sum = nums[i + j + 1] + prod; //这3行很重要!
                nums[i + j + 1] = sum % 10;
                nums[i + j] += sum / 10;
class Solution {
public:
    string multiply(string num1, string num2) {
        int m = num1.size(), n = num2.size();
        vector<int> nums(m + n, 0);
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int prod = (num1[i] - '0') * (num2[j] - '0');
                int sum = nums[i + j + 1] + prod; //这3行很重要!
                nums[i + j + 1] = sum % 10;
                nums[i + j] += sum / 10;
            }
        }
        string res = "";
        for (int i = 0; i < m + n; i++) {
            res += nums[i] + '0';
        }
        while (res[0] == '0' && res.size() > 1) res = res.substr(1); //for "0*0", 至少要返回一个"0",不能返回空。
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值