![](https://img-blog.csdnimg.cn/70b87cd957354190b4216469c745cf88.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAd3d3c2N0dmNvbQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
解题思路:
![](https://img-blog.csdnimg.cn/37ee0bdff34645e19b3a6fad5be3d749.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAd3d3c2N0dmNvbQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
代码
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
string ans;
int m = num1.size(), n = num2.size();
// 依次用num2的值乘num1的每个值
for (int i = n-1; i >= 0; i--) {
string cur;
int add = 0;
// 计算补零的个数
for (int j = n-1; j > i; j--) {
cur.push_back(0);
}
// 计算乘积
int y = num2.at(i) - '0';
for (int j = m-1; j >= 0; j--) {
int x = num1.at(j) - '0';
int product = x * y + add;
cur.push_back(product % 10);
add = product / 10;
}
// 进位
while (add != 0) {
cur.push_back(add % 10);
add /= 10;
}
// 翻转
reverse(cur.begin(), cur.end());
for(auto &c : cur) {
c += '0';
}
ans = addStrings(ans, cur);
}
return ans;
}
string addStrings(string &num1, string &num2) {
int i = num1.size()-1, j = num2.size()-1, add = 0;
string ans;
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.at(i) - '0' : 0;
int y = j >= 0 ? num2.at(j) - '0' : 0;
int result = x + y + add;
ans.push_back(result % 10);
add = result / 10;
i--;
j--;
}
reverse(ans.begin(), ans.end());
for (auto &c : ans) {
c += '0';
}
return ans;
}
};