给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
代码如下:
class Solution {
public:
string multiply(string num1, string num2) {
int l1 = num1.size();
int l2 = num2.size();
string res = "";
vector<int> product(l1 + l2, 0); // 存储乘积的数组
int t = 0, x = 0;
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
for(int i = 0; i < l1; i++){
for(int j = 0; j < l2; j++){
product[i + j] += (num2[j] - '0') * (num1[i] - '0');
}
}
for (int i = 0; i < l1 + l2; i++) {
x = product[i] + t;
res.push_back(x % 10 + '0');
t = x / 10;
}
while (t > 0) {
res.push_back(t % 10 + '0');
t /= 10;
}
reverse(res.begin(),res.end());
// 去除前导零
int i = 0;
while (res[i] == '0' && i < res.size() - 1) {
i++;
}
res = res.substr(i);
return res;
}
};
思路:从低位相乘,用product存储每一位相乘的乘积,t表示进位,将(每一个存储的乘积+进位)对10取余,得到相乘后每一位的数字,将(每一个存储的乘积+进位)除以10,得到进位t,最后去除前导0(我这里写麻烦了,之间从后往前遍历就行了,没必要用reverse)