您的位置:首页 > 其它

LeetCode | 43. Multiply Strings(大整数乘法)

2017-06-26 01:09 666 查看
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.


大整数乘法,6ms AC

#include <iostream>
#include <string>
using namespace std;

string multiply(string num1, string num2)
{
//i 和 j 相乘的结果是 res 的 (i+j) 位
string str_res = "";
int first = 0;
int res[300] = {};
int len1 = num1.length(), len2 = num2.length();
if(len1 < len2)
return multiply(num2, num1);
int a[120] = {};
int b[120] = {};

for(int i=0;i<len1;i++)
a[i] = num1[len1-i-1]-'0';
for(int i=0;i<len2;i++)
b[i] = num2[len2-i-1]-'0';

for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
res[i+j] += a[i]*b[j];
}
}

for(int i=0;i<len1+len2+2;i++)
{
if(res[i] >= 10)
{
res[i+1] += res[i]/10;
res[i] %= 10;
}
}

for(int i=290;i>=0;i--)
if(res[i] != 0)
{
first = i; break;
}
for(int i=first;i>=0;i--)
{
str_res += res[i]+'0';
}

return str_res;
}

int main()
{
string str1, str2;
while(cin>>str1>>str2)
{
cout<<multiply(str1, str2)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode