题目链接:https://leetcode.com/problems/multiply-strings/#/solutions
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.
方法一:
class Solution{
public:
string multiply(string num1,string num2)
{
if(num1.empty() || num2.empty())
return string();
if(num1=="0" || num2=="0")
return "0";
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
int len1=num1.length(),len2=num2.length();
string ret="";
int carry=0;
for(int i=0;i<len1;i++)
{
size_t pos=i;
for(int j=0;j<len2;j++)
{
int temp=(num1[i]-'0')*(num2[j]-'0')+carry;
if(pos<ret.length())
{
temp=temp+(ret[pos]-'0');
ret[pos]=temp%10+'0';
}
else
{
ret.append(1,temp%10+'0');
}
carry=temp/10;
pos++;
}
if(carry>0)
ret.append(1,carry+'0');
carry=0;
}
reverse(ret.begin(),ret.end());
return ret;
}
};
方法二:
string multiply(string num1, string num2) {
string sum(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; 0 <= i; --i) {
int carry = 0;
for (int j = num2.size() - 1; 0 <= j; --j) {
int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
sum[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
sum[i] += carry;
}
size_t startpos = sum.find_first_not_of("0");
if (string::npos != startpos) {
return sum.substr(startpos);
}
return "0";
}