先贴上代码

 public String multiply(String num1, String num2) {
String str = "";
StringBuffer sb = new StringBuffer(num1);
num1 = sb.reverse().toString();
sb = new StringBuffer(num2);
num2 = sb.reverse().toString();
int[] res = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
for (int j = 0; j < num2.length(); j++) {
res[i + j] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
}
}
int k = 0, contribute = 0;
while (k < res.length || contribute > 0) {
int tmp = k<res.length?res[k]:0;
tmp = contribute+tmp;
contribute = tmp/10;
str += tmp%10;
k++;
}
sb = new StringBuffer(str);
str = sb.reverse().toString();
int i = 0;
while(i<str.length()&&str.charAt(i)=='0')
i++;
if(i<str.length()){
str = str.substring(i);
}else{
str = "0";
}
return str;
}

思路如下:

模拟竖式相乘

1、转换并反转,字序反转;
2、逐位相乘,结果存放在res[i+j]中;
3、处理进位;
4、转换并反转,将计算结果转换为字符串并反转。
5、消除多余的0;

两数相乘,结果的长度一定不大于乘数和被乘数的长度之和。

Multiply Strings 大数相乘 java-LMLPHP

上述也可以用直接用java的BigInteger类实现

public static void main(String[] args) {
String a = "98989898989898956898", b = "989892551548781251323265615150";
BigInteger aa = new BigInteger(a);
BigInteger bb = new BigInteger(b);
System.out.println(aa.multiply(bb)); }
05-11 17:30