您的位置:首页 > 其它

43. Multiply Strings

2015-11-02 15:45 274 查看
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.

思路:

利用竖式的思想,进行乘法运算。

3 4

* 1 3

——————

9 12

3 4

——————

3 13 12

再处理进位:

3 13 12 - > 3 14 2 -> 4 4 2

class Solution {
public:
string multiply(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int carry = 0;
string result;
int len1 = num1.length();
int len2 = num2.length();
int resLen = len1+len2-1;
for(int resPos = 0; resPos<resLen;++resPos) //indicate the pos of the result
{
int sum = 0;
for(int i = max(0,resPos-len2+1); i < len1; ++i) //traverse the digit of num1
{
int j = resPos-i; //indicate the pos of num2
if(j < 0) break;
sum += (num1[i]-'0')*(num2[j]-'0');
}
sum += carry;
result.push_back(sum % 10+'0');
carry = sum/10;
}

while(carry > 0)
{
result.push_back(carry % 10+'0');
carry /= 10;
}
reverse(result.begin(), result.end());
if(result.find_first_not_of('0') == string::npos) return "0";//排除全0的情况
else return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: