如“111111111111111”和“222222222222222”,输出乘积“24691358024691308641975308642”。
== 不使用Java中的BigInteger等类==
public class BigIntegerMultiplication {
public static void main(String[] args) {
System.out.println(IntegerMultiplication("111111111111111","222222222222222"));
}
public static String IntegerMultiplication(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
int carry = 0;
String strTemp = "";//存储每次分治结果
String res = "";
String jz="";//补0
for (int i = 0; i < chars1.length; i++) {
if(i!=0){
jz+="0";
}
int temp = chars1[chars1.length - i - 1] - '0';
strTemp="";
for (int j = 0; j < chars2.length; j++) {
int temp2 = temp * ((chars2[chars2.length - j - 1] - '0'));
int temp3=temp2+carry;
strTemp = temp3%10+""+strTemp;
carry = temp3 > 10 ? temp3 / 10 : 0;
}
res = IntegerAdd(res,strTemp+jz);
}
return res;
}
public static String IntegerAdd(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
String res = "";
int carry = 0;//进位
char[] chars3 = chars1.length >= chars2.length ? chars1 : chars2;
char[] chars4 = chars3== chars1 ? chars2 : chars1;
for (int i = 0; i < chars3.length; i++) {
int temp = chars3[chars3.length - i - 1] - '0';
int temp2=0;
if(i<chars4.length) {
temp2 =chars4[chars4.length - i - 1] - '0';
}
int temp3=temp+temp2;
res = (temp3)%10 + carry +res;
carry = (temp3) > 10 ? (temp3) / 10 : 0;
}
return res;
}
}