Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
class Solution {
public:
string multiply(string num1, string num2) {
const int n1 = num1.size();
const int n2 = num2.size();
string res(n1+n2, '0');
for (int i = n2 - 1; i >= 0; i--) {
for (int j = n1-1, k = n1 + i; j >= 0; j--,k--) {
int t = (num2[i]-'0')*(num1[j]-'0') + (res[k]-'0');
int ind = 0;
while (k-ind >= 0 && t) {
res[k-ind] = (t%10 + '0');
ind++;
t = t/10 + (res[k-ind]-'0');
}
}
}
int i = 0;
while (i < n1+n2 && res[i] == '0') {
i++;
}
return i == n1+n2?"0":res.substr(i, n1+n2-i);
}
};
本文介绍了一种用于计算两个任意大数相乘的方法,该方法通过将字符串表示的数字转换为数值相乘后再转化为字符串输出,适用于处理非常大的数字。通过内部循环和位运算实现,确保了算法的效率和正确性。
183

被折叠的 条评论
为什么被折叠?



