您的位置:首页 > 其它

LeetCode: Multiply Strings

2016-10-31 20:17 351 查看
题目:

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.

题目给出两个字符串形式的数,要求出两个数乘积的字符串形式。

由于数字可能很大,因此把给定的数字装换为整数做乘法后可能会溢出。所以,应一步步在算法中做乘法运算,为避免溢出,用数组保存每一位的结果,最后将数组中保存的结果转化为字符串。Accepted的代码:

class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0"||num2=="0") return "0";
int m=num1.length();//第一个数字的位数
int n=num2.length();//第二个数字的位数

//保存每一位的结果,初始化为0
vector<int> results;
for(int i=0;i<m+n;i++) results.push_back(0);

int c=0;//保存进位
int index=0;//缩进
//计算过程
for(int i=m-1;i>=0;i--)//乘数
{
for(int j=n-1;j>=0;j--)//被乘数
{
int value=(num1[i]-'0')*(num2[j]-'0')+c;
results[index+n-1-j]+=value%10;
c=value/10;
if(results[index+n-1-j]>=10)
{
results[index+n-1-j]-=10;
c++;
}

}
results[index+n]+=c;
c=0;
index++;
}
//去除前面的0
int i;
for(i=m+n-1;i>=0;i--)
if(results[i]!=0) break;
//将结果转换为字符串
string str;
for(int j=i;j>=0;j--)
{
char ch=results[j]+'0';
str+=ch;
}
return str;
}
};


算法的复杂度为o(mn),m和n分别为两个数字的位数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: