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);
}
};
结果: