题目:
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.
Solution:
思路:
乘数为num1和num2,则模拟手算,每次更新num1位,要加上进位,若需再往前更新,设置个迭代。
代码如下:
string multiply(string num1, string num2)
{
int len1 = num1.size();
int len2 = num2.size();
int len = len1+len2;
string result(len,'0'); //两数相乘,位数最多len1+len2
int a,b,c,d,w,k,t,i,j;
for(i = len1-1;i>=0;i--)
{
d = 0;
for(j = len2-1,k = len2+i;j>=0;j--,k--)
{
a = num1[i] - '0';
b = num2[j] - '0';
c = result[k] - '0';
t = a*b +c+d;
result[k] = t %10 + '0';
d = t/10;
if(j == 0 && d!= 0)
{
w = k-1;
t = result[w] - '0' + d;
result[w] = t%10 + '0';
while(t >=10 && w>0)
{
result[w] = t %10 +'0';
w--;
d = t/10;
t = result[w] - '0' + d;
}
}
}
}
i = 0;
while(i < result.size() && result[i] - '0' == 0)
i++;
result = result.substr(i,len-i);
if(result == "")
return "0";
return result;
}