思路
用一个数组记录乘积的结果,最后处理进位。
代码
class Solution {
public:
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0") return "0";
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int a[num1.length() + num2.length() + 1] = {0};
for(int i = 0; i < num1.length(); i++){
for(int j = 0; j < num2.length(); j++){
a[i + j] += (num1[i] - '0') * (num2[j] - '0');
}
}
int mod = 0;
for(int i = 0; i <= num1.length() + num2.length(); i++){
a[i] += mod;
mod = a[i] / 10;
a[i] %= 10;
}
int i = num1.length() + num2.length();
while(!a[i]) i--;
string ans = "";
while(i >= 0){
ans += a[i] + '0';
i--;
}
return ans;
}
};
原文地址:https://www.cnblogs.com/woxiaosade/p/12377361.html
时间: 2024-11-07 18:33:35