Multiply Strings
Total Accepted: 30373 Total Submissions: 145134
Question Solution
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.
分析:大数乘法,思路将两个乘数分别切两半,交叉相乘递归运算,最后汇总计算结果,最大的问题就是位移要考虑清楚以0填位,计算时要考虑进位问题,另外当两个数相乘是有一个数为0的特殊情况,运算结果直接为0
public class Solution {
String multi(String x, String y, int xp, int yp)
{
int xl=x.length();
int yl=y.length();
if(xl==1)
{
int a=x.charAt(0)-'0';
int jinwei=0;
String result="";
if(a==0)
{
result="0";
return result;
}
for(int i=yl-1;i>=0;i--)
{
int b=y.charAt(i)-'0';
int sum=a*b+jinwei;
jinwei=sum/10;
result=Integer.toString(sum%10)+result;
}
if(jinwei>0)
result=Integer.toString(jinwei)+result;
int k=0;
while(k<xp+yp)
{
result=result+"0";
k++;
}
return result;
}
else if(yl==1)
{
int a=y.charAt(0)-'0';
int jinwei=0;
String result="";
if(a==0)
{
result="0";
return result;
}
for(int i=xl-1;i>=0;i--)
{
int b=x.charAt(i)-'0';
int sum=a*b+jinwei;
jinwei=sum/10;
result=Integer.toString(sum%10)+result;
}
if(jinwei>0)
result=Integer.toString(jinwei)+result;
int k=0;
while(k<xp+yp)
{
result=result+"0";
k++;
}
return result;
}
else
{
String ll=multi(x.substring(0,xl/2),y.substring(0,yl/2),xl-xl/2,yl-yl/2);
String lr=multi(x.substring(0,xl/2),y.substring(yl/2,yl),xl-xl/2,0);
String rl=multi(x.substring(xl/2,xl),y.substring(0,yl/2),0,yl-yl/2);
String rr=multi(x.substring(xl/2,xl),y.substring(yl/2,yl),0,0);
int l_ll=ll.length();
int l_rl=rl.length();
int l_lr=lr.length();
int l_rr=rr.length();
int L=l_ll;
if(l_rl>L)
L=l_rl;
if(l_lr>L)
L=l_lr;
if(l_rr>L)
L=l_rr;
int i=0;
int jinwei=0;
String outcome="";
while(L-i>0)
{
int sum=0;
if(l_ll-i>0)
sum=sum+ll.charAt(l_ll-1-i)-'0';
if(l_rl-i>0)
sum=sum+rl.charAt(l_rl-1-i)-'0';
if(l_lr-i>0)
sum=sum+lr.charAt(l_lr-1-i)-'0';
if(l_rr-i>0)
sum=sum+rr.charAt(l_rr-1-i)-'0';
sum=sum+jinwei;
jinwei=sum/10;
sum=sum%10;
outcome=Integer.toString(sum)+outcome;
i++;
}
if(jinwei>0)
outcome=Integer.toString(jinwei)+outcome;
int k=0;
while(k<xp+yp)
{
outcome=outcome+"0";
k++;
}
return outcome;
}
}
public String multiply(String num1, String num2) {
return multi(num1,num2,0,0);
}
}