Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:
1 翻转string
2 建立数组,双层循环遍历两个string,把单位的乘积累加到数组相应的位置
3 处理进位并输出
4 再把结果翻转
5 注意前导零的corner case
class Solution {
public:
string multiply(string num1, string num2) {
if(num1.size()==0 || num2.size()==0)
return string();
if(num1=="0" || num2=="0")
return "0";
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
int n1 = num1.size();
int n2 = num2.size();
int d[n1+n2] = {0};
for(int i=0;i<n1;i++)
{
for(int j =0;j<n2;j++)
{
d[i+j] += (num1[i]-'0') * (num2[j]-'0');
}
}
string res;
for(int i=0;i<n1+n2;i++)
{
int digit = d[i]%10;
int carry = d[i]/10;
if(i+1<n1+n2)
d[i+1] += carry;
res.push_back(digit+'0');
}
reverse(res.begin(),res.end());
int i=0;
while(res[i]=='0')
{
i++;
}
string res1 = res.substr(i,res.size());
return res1;
}
};