把两个字符串倒过来以后对应位置相乘,注意最终结果要去掉最前面的0
class Solution {
public:
string multiply(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
string s(num1.size() + num2.size(), ‘0‘);
for (size_t i = 0; i < num1.size(); i++)
{
for (size_t j = 0; j < num2.size(); j++)
{
s[i + j] = s[i + j] - ‘0‘ + (num2[j] - ‘0‘)*(num1[i] - ‘0‘);
s[i + j + 1] = s[i + j + 1] + s[i + j] / 10;
s[i + j] = s[i + j] % 10 + ‘0‘;
}
}
int notZeroIndex = s.size() - 1;
while (s[notZeroIndex] == ‘0‘ && notZeroIndex>0)
{
notZeroIndex--;
}
s = s.substr(0, notZeroIndex + 1);
reverse(s.begin(), s.end());
return s;
}
};
原文:http://www.cnblogs.com/flyjameschen/p/4381226.html