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.
字符串相乘,即用string来实现大数的乘法
class Solution {
public:
string multiply(string num1, string num2) {
if(num1.length()<num2.length()){
string yes = num2;
num2 = num1;
num1 = yes;
}
string str="0";
for(int i=0;i<num2.length();i++){
string tmp = multi(num1,num2[num2.length()-1-i]);
tmp = tmp+getZero(i);
str = add(str,tmp);
}
return str;
}
string getZero(int n){
string str="";
for(int i=0;i<n;i++)
str+='0';
return str;
}
string multi(string num,char c){
if(c=='0')
return "0";
int r = 0;
int tmp;
int y = c-'0';
string str="";
for(int i=0;i<num.length();i++){
int x = num[num.length()-1-i]-'0';
tmp = x*y+r;
r = tmp/10;
char c = tmp%10+'0';
str = c +str;
}
while(r>0){
char c = r%10+'0';
str = c+str;
r/=10;
}
return str;
}
string add(string num1,string num2){
if(num1.length()<num2.length()){
string yes = num2;
num2 = num1;
num1 = yes;
}
if(num2=="0")
return num1;
int r = 0;
string str="";
int i;
for(i=0;i<num2.length() && i<num1.length();i++){
int tmp = num1[num1.length()-1-i]-'0'+num2[num2.length()-1-i]-'0'+r;
r=tmp/10;
char c = tmp%10+'0';
str = c+str;
}
while(i<num1.length()){
int tmp = num1[num1.length()-1-i]-'0'+r;
r=tmp/10;
char c = tmp%10+'0';
str = c+str;
i++;
}
if(r!=0){
str = '1'+str;
}
return str;
}
};