您的位置:首页 > 其它

leetcode 43:Multiply Strings

2015-11-04 20:25 387 查看
题目:

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.

思路:

可以按照我们一般做乘法的思路,用一个数的每一位去乘另一个数的每一位,将结果加在对应结果位中。结果的位数从第一位到(n1+n2)位。

时间复杂度O(n1*n2),空间复杂度O(n1+n2)。

需要注意两个进位操作,第一是两个位数相乘后的进位,第二个是将相乘结果相加时产生的进位。

第一个进位直接加到下一次乘积结果中,第二个进位则要加在高位的结果位中。

实现如下:

class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
string result(size1+size2,'0');
int mul = 0, carry = 0;
for (int i = size1 - 1; i >= 0; i--)
{
carry = 0;
int index = size1-1-i;
for (int j = size2 - 1; j >= 0; j--)
{
mul = (num1[i] - '0')*(num2[j] - '0');
int temp=result[index]-'0' + mul % 10 + carry ;
result[index + 1] += temp / 10;
result[index] = temp % 10 + '0';
carry = mul / 10;
index++;
}
result[index] += carry;
}
int pos = size1 + size2 - 1;
while (pos>0 && result[pos] == '0') pos--;
result[pos + 1] = '\0';
for (int i = 0; i <= pos / 2; i++)
{
swap(result[i],result[pos-i]);
}
return result.substr(0,pos+1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: