Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
竖式乘法
用String类型的 res 表示计算结果
res[i+j+1]
累加储存 sum%10
,res[i+j]
累加储存 sum/10
。
res[i+j] += sum/10
用+=
表示累加,
而res[i+j+1] = sum % 10 + '0'
不用+=
,
是因为前面的操作int sum = (num1[i] - '0')*(num2[j] - '0') + (res[i+j+1]-'0');
,sum
已经累加了res[i+j+1]
C++
class Solution {
public:
string multiply(string num1, string num2) {
int n1=num1.size();
int n2=num2.size();
string res(n1+n2,'0');//2数相乘, 商的长度必定不可能大于2数的长度之和 size1 + size2
for(int i=n1-1;i>=0;i--){
for(int j=n2-1;j>=0;j--){
int sum = (num1[i] - '0')*(num2[j] - '0') + (res[i+j+1]-'0');
res[i+j+1] = sum % 10 + '0';
res[i+j] += sum/10; //string 内的字符 加上int 自动转化为char,不必加'0'
}
}
//消前置零
for(int i = 0; i < n1+n2; i++){
if(res[i]!='0'){
return res.substr(i);
}
}
return "0";
}
};