乘法运算可以分拆为两步:第一步,是将乘数与被乘数逐位相乘;第二步,将逐位相乘得到的结果,对应相加起来。
具体原理看图:http://blog.csdn.net/sunkun2013/article/details/11822927
public class BigInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
int[] num1 = new int[str1.length()];
int[] num2 = new int[str2.length()];
//把字符串转换成int数组
for (int i = 0; i < str1.length(); i++) {
num1[str1.length() - 1 - i] = str1.charAt(i) - '0';
}
for (int i = 0; i < str2.length(); i++) {
num2[str2.length() - 1 - i] = str2.charAt(i) - '0';
}
int[] result = multiply(num1, num2);
// 因为前面做了倒序操作,所以最高位在最后
for (int i = result.length - 1; i >= 0; i--) {
if(i==result.length - 1)
if(result[i]==0)
continue;
System.out.print(result[i]);
}
sc.close();
}
public static int[] multiply(int[] num1, int[] num2) {
int lengthOfNum1 = num1.length;
int lengthOfNum2 = num2.length;
//如果num1和num2的长度分别为n1,n2,那么它们相乘的结果位数最大为n1+n2
int[] result = new int[lengthOfNum1 + lengthOfNum2];
//num[i]*num2[j]的结果存在result[i+j]上,最后再处理进制问题
for (int i = 0; i < lengthOfNum1; i++) {
for (int j = 0; j < lengthOfNum2; j++) {
result[i + j] += num1[i] * num2[j];
}
}
// 处理进制问题
for (int i = 0; i < lengthOfNum1 + lengthOfNum2 - 1; i++) {
if (result[i] >= 10) {
result[i + 1] += result[i] / 10;
result[i] = result[i] % 10;
}
}
return result;
}
}