题目描述
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.
class Solution {
public:
string multiply(string num1,string num2)
{
int n=num1.size();
int m=num2.size();
if(n==0||m==0)
return "";
string result="";
long long k=toi(num2);
if(k==1)
return num1;
if(k==0||toi(num1)==0)
return "0";
vector<string> rd;
int kf=0;
for(int i=m-1;i>=0;i--)
{
string s=""+string(kf++,'0');
int s2=0;
int k2=num2[i]-48;
for(int j=n-1;j>=0;j--)
{
int k1=num1[j]-48;
s+=char(((k1*k2)+s2)%10+48);
s2=((k1*k2)+s2)/10;
}
if(s2!=0)
s+=char(s2+48);
reverse(s.begin(),s.end());
rd.push_back(s);
}
for(int i=0;i<rd.size();i++)
{
result=multiply_k(rd[i], result);
}
return result;
}
long long toi(string num2)
{
long long result=0;
int n=num2.size();
int s=1;
result+=num2[n-1]-48;
for(int i=n-2;i>=0;i--)
{
s*=10;
result+=(num2[i]-48)*s;
}
return result;
}
string multiply_k(string num1, string num2)
{
int s=0;
string result="";
int n=num1.size();
int m=num2.size();
if(m==0)
return num1;
if(n==0)
return num2;
int i=n-1,j=m-1;
while(i>=0&&j>=0)
{
vector<int> k;
f(num1[i]-48,num2[j]-48,s,k);
s=k[0];
result+=char(k[1]+48);
i--;
j--;
}
while(i>=0)
{
int kf=num1[i]+s-48;
s=kf/10;
result+=char(kf%10+48);
i--;
}
while(j>=0)
{
int kf=num2[j]+s-48;
s=kf/10;
result+=char(kf%10+48);
j--;
}
if(s!=0)
result+=char(s+48);
reverse(result.begin(),result.end());
return result;
}
void f(int i,int j,int s,vector<int>&fd)
{
int result=i+j+s;
fd.push_back(result/10);
fd.push_back(result%10);
}
};