AC代码:
class Solution {
public:
string multiply(string num1, string num2) {
string res(num1.size()+num2.size(),'0');
for(int i = num1.size() - 1;i >= 0;i--)
{
int carry = 0;
for(int j = num2.size() - 1;j >= 0;j--)
{
int tmp = res[i+j+1]-'0' + (num1[i] - '0')*(num2[j]-'0') + carry;
res[i+j+1] = tmp%10 + '0';
carry = tmp/10;
}
res[i] += carry;
}
size_t start = res.find_first_not_of("0");
if(start != string::npos)
return res.substr(start);
return "0";
}
};
这道题目最关键的一点是要理解,针对一个m位 和n位字符串相乘,结果最多m+n位。
我们以"123" "234"为例,循环刚开始时i为2,j为2,结果位应该保存在res[5],即res[i+j+1];
最后就是需要去掉前导0,返回无前导0子串。进位问题也需要注意,以"123"和"456"为例添加打印:
000368 i = 2 carry = 1
009488 i = 1 carry = 0
055088 i = 0 carry = 0
实际上此时可以理解成j==-1,最终更新一次res[i+j+1],即res[i].
运行效率:
Runtime: 4 ms, faster than 88.31% of C++ online submissions for Multiply Strings.
Memory Usage: 6.2 MB, less than 99.03% of C++ online submissions for Multiply Strings.
更好理解的代码如下:
class Solution {
public:
string multiply(string num1, string num2) {
string res(num1.size() + num2.size(),'0');
int m = num1.size(),n = num2.size();
for(int i=m-1;i>=0;i--)
{
for(int j=n-1;j>=0;j--)
{
int sum = res[i+j+1] - '0' + (num1[i] - '0')*(num2[j] - '0');
res[i+j+1] = sum % 10 + '0';
res[i+j] += sum /10;
}
}
for(int i = 0;i < m + n;i++)
{
if(res[i] != '0')
return res.substr(i);
}
return "0";
}
};
运行效率:
Runtime: 4 ms, faster than 88.46% of C++ online submissions for Multiply Strings.
Memory Usage: 6.4 MB, less than 93.69% of C++ online submissions for Multiply Strings.