您的位置:首页 > 其它

leetcode---Multiply Strings---大整数乘法

2016-05-26 21:53 531 查看
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.

Converting the input string to integer is NOT allowed.

You should NOT use internal library such as BigInteger.

class Solution {
public:
string multiply(string num1, string num2)
{
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int l1 = num1.size();
int l2 = num2.size();
int ans[l1+l2];
memset(ans, 0, sizeof(ans));
for(int i=0; i<l1; i++)
for(int j=0; j<l2; j++)
ans[i+j] += (num1[i] - '0') * (num2[j] - '0');

int c = 0;
int i = 0;
while(i < l1 + l2 - 1 || c)
{
int s = ans[i] + c;
ans[i] = s % 10;
c = s / 10;
i++;
}
string result = "";
i = l1 + l2 - 1;
while(i && ans[i] == 0) //去掉前面的0
i--;
if(i == 0 && ans[i] == 0)
return "0";
while(i >= 0)
{
result = result + (char)(ans[i] + '0');
i--;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: