Multiply Strings
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 {
private:
void reverse(string& s)
{
int l=0;
int r=s.length()-1;
while(l<r)
{
char c=s[l];
s[l]=s[r];
s[r]=c;
l++;
r--;
}
}
void add(string& s1,string s2)
{
while(s1.length()<s2.length()) s1=s1+'0';
while(s2.length()<s1.length()) s2=s2+'0';
int add=0;
for(int i=0;i<s1.length();i++)
{
int sum=add+s1[i]+s2[i]-'0'-'0';
s1[i]=sum%10+'0';
add=sum/10;
}
if(add>0) s1=s1+char(add+'0');
}
void mul(string& s,int n)
{
int add=0;
for(int i=0;i<s.length();i++)
{
int sum=(s[i]-'0')*n+add;
s[i]=sum%10+'0';
add=sum/10;
}
if(add>0) s=s+char('0'+add);
}
void fix(string& s)
{
if(s.length()==0) s="0";
int index=s.length()-1;
while(index>0 && s[index]=='0') index--;
string result;
for(int i=0;i<=index;i++)
result=result+s[i];
s=result;
}
public:
string multiply(string num1, string num2)
{
reverse(num1);
reverse(num2);
string result;
string tens;
for(int i=0;i<num2.length();i++)
{
string num=num1;
mul(num,num2[i]-'0');
num=tens+num;
add(result,num);
tens=tens+'0';
}
fix(result);reverse(result);
return result;
}
};
private:
void reverse(string& s)
{
int l=0;
int r=s.length()-1;
while(l<r)
{
char c=s[l];
s[l]=s[r];
s[r]=c;
l++;
r--;
}
}
void add(string& s1,string s2)
{
while(s1.length()<s2.length()) s1=s1+'0';
while(s2.length()<s1.length()) s2=s2+'0';
int add=0;
for(int i=0;i<s1.length();i++)
{
int sum=add+s1[i]+s2[i]-'0'-'0';
s1[i]=sum%10+'0';
add=sum/10;
}
if(add>0) s1=s1+char(add+'0');
}
void mul(string& s,int n)
{
int add=0;
for(int i=0;i<s.length();i++)
{
int sum=(s[i]-'0')*n+add;
s[i]=sum%10+'0';
add=sum/10;
}
if(add>0) s=s+char('0'+add);
}
void fix(string& s)
{
if(s.length()==0) s="0";
int index=s.length()-1;
while(index>0 && s[index]=='0') index--;
string result;
for(int i=0;i<=index;i++)
result=result+s[i];
s=result;
}
public:
string multiply(string num1, string num2)
{
reverse(num1);
reverse(num2);
string result;
string tens;
for(int i=0;i<num2.length();i++)
{
string num=num1;
mul(num,num2[i]-'0');
num=tens+num;
add(result,num);
tens=tens+'0';
}
fix(result);reverse(result);
return result;
}
};