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.
Solution1
- 最简单的方法就是完全模拟乘法的运算规则,下面的代码是用了两个辅助函数,其中help1方法是用来计算第一个数和个位数相乘的,help2是用来对两个字符串代表的数进行求和的。
public class Solution {
public String multiply(String num1, String num2) {
if(num1.length()==0||num2.length()==0) return "";
String result = "", zeros = "";
for(int i=num2.length()-1;i>=0;i--,zeros += "0"){
int num = num2.charAt(i) - '0';
if(num==0) continue;
else if(num==1) result = help2(result,num1+zeros);
else result = help2(result,help1(num1,num)+zeros);
}
return result==""?"0":result;
}
public String help1(String num1, int num){//大数和个位数相乘
String s = "";
int ci = 0;
for(int i=num1.length()-1;i>=0;i--){
int temp = (num1.charAt(i)-'0')*num + ci;
s = String.valueOf(temp%10) + s;
ci = temp/10;
}
if(ci!=0) s = String.valueOf(ci) + s;
return s;
}
public String help2(String s1, String s2){//大数相加
String s = "";
for(int i=s1.length()-1,j=s2.length()-1,ci=0;i>=0||j>=0||ci>0;){
int temp = (i>=0?s1.charAt(i--)-'0':0) + (j>=0?s2.charAt(j--)-'0':0) + ci;
s = String.valueOf(temp%10) + s;
ci = temp/10;
}
return s;
}
}
Solution2
- 上面的方法虽然能解,但是过于繁琐,并且容易出错。下面给出一种更优化的方法。对照着数仔细体会其中的过程。
public class Solution {
public String multiply(String num1, String num2) {
int n1 = num1.length();
int n2 = num2.length();
int[] product = new int[n1+n2];
for(int i=n1-1;i>=0;i--){
for(int j=n2-1;j>=0;j--){
int index = n1+n2-i-j-2;
product[index] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
product[index+1] += product[index]/10;
product[index] %= 10;
}
}
StringBuffer sb = new StringBuffer();
for(int i=n1+n2-1;i>=0;i--){
if(sb.length()==0&&product[i]==0) continue;
sb.append(product[i]);
}
return sb.length()==0?"0":sb.toString();
}
}