您的位置:首页 > 其它

Multiply Strings ---leetcode

2016-07-18 16:21 288 查看
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.

Subscribe to see which companies asked this question
这是来自于leetcode上的一道算法题目。
算法思路:用char存储大数的每一位,然后控制每一位之间的相乘和进位即可。
我的代码如下:
class Solution {
public:
string multiply(string num1, string num2) {
const char *ch1 = num1.c_str();
const char *ch2 = num2.c_str();
const unsigned int l1=num1.length();
const unsigned int l2=num2.length();
const unsigned int lc = l1 +l2 +1;
//cout<<str1.length()+str2.length()+1<<endl;
char *ch3 = (char *)malloc((lc+1)*sizeof(char));
for (int i = 0; i < lc; i++)
{
ch3[i]='0';
}
for (int i = l1 - 1; i >= 0 ; i--)
{
unsigned int start = (l1-i);
int re = 0;
for (int j = l2 - 1; j >= 0 ; j--)
{
int temp = (ch1[i]-48)*(ch2[j]-48) + re;
int result = ch3[lc - (l1-i)-(l2-j)]+(temp%10) -48;
re =temp/10;
if (result>9)
{
re+=result/10;
result=result%10;
}
ch3[lc - (l1-i)-(l2-j)]= result+48;
if (j==0)
{
ch3[lc - (l1-i)-(l2-j)-1]=re+48;
}
}
}
string a(ch3);
free(ch3);
int i=0;
for(;i<lc-2;i++){
if(a.substr(i,1)=="0")continue;
else break;
}
return a.substr(i,lc-i-1);
}
};结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息