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 multiply(string num1, string num2) {
int lena=num1.length(),lenb=num2.length();
if(lena==0||lenb==0)
return "";
if(num1=="1")
return num2;
if(num2=="1")
return num1;
if(num1=="0"||num2=="0")
return "0";
int cura=lena-1;
int curb=lenb-1;
string res(lena+lenb,‘0‘);
for(int i=cura;i>=0;i--){
int carry=0;
for(int j=curb;j>=0;j--){
int temp=res[i+j+1]-‘0‘+(num1[i]-‘0‘)*(num2[j]-‘0‘)+carry;
res[i+j+1]=temp%10+‘0‘;
carry=temp/10;
}
res[i]+=carry;//这里本来应该是s[i+j]得到进位数,但因为innerloop后,j=0,
}
int pos=res.find_first_not_of(‘0‘);
if(pos==string::npos)
return "0";
return res.substr(pos);
}
原文地址:http://searchcoding.blog.51cto.com/1335412/1694850