这道题大整数的乘法,和加法一样,需要按位计算然后加起来即可。但是有一个问题要注意的是这里的乘法积很可能非常大,因此需要用数组来储存。在计算的时候数组元素可以大于9,之后再历遍进位即可。
public class Solution {
public String multiply(String num1, String num2) {
if(num1==null||num2==null)
return "";
if(num1.length()==1&&Integer.parseInt(num1)==0||num2.length()==1&&Integer.parseInt(num2)==0)
return "0";
//using StringBuilder in building String
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
int[] sa = new int[n1.length()+n2.length()];
for(int i=0;i<n1.length();i++){
for(int j=0;j<n2.length();j++){
//switching char to int. Cannot us (int)'a'. Another way is Integer.parseInt('a'+"");
sa[i+j]+=(n1.charAt(i)-'0')*(n2.charAt(j)-'0');
}
}
for(int i=0;i<sa.length-1;i++){
sa[i+1]+= sa[i]/10;
sa[i]=sa[i]%10;
}
boolean flag=false;
StringBuilder res = new StringBuilder();
for(int i=sa.length-1;i>=0;i--){
if(flag==false&&sa[i]!=0)
flag=true;
if(flag){
res.append(sa[i]);
}
}
return res.toString();
}
}
Update 2015/08/31:下面是九章的解法,都差不多
public class Solution {
public String multiply(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
}
int len1 = num1.length(), len2 = num2.length();
int len3 = len1 + len2;
int i, j, product, carry;
int[] num3 = new int[len3];
for (i = len1 - 1; i >= 0; i--) {
carry = 0;
for (j = len2 - 1; j >= 0; j--) {
product = carry + num3[i + j + 1] +
Character.getNumericValue(num1.charAt(i)) *
Character.getNumericValue(num2.charAt(j));
num3[i + j + 1] = product % 10;
carry = product / 10;
}
num3[i + j + 1] = carry;
}
StringBuilder sb = new StringBuilder();
i = 0;
while (i < len3 - 1 && num3[i] == 0) {
i++;
}
while (i < len3) {
sb.append(num3[i++]);
}
return sb.toString();
}
}