- 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;
}
};