package algorithm.factorial;
import java.util.Arrays;
/**
* @describe: 大数相乘问题
* @author: morningcat.zhang
* @date: 2020/5/17 4:27 PM
*/
public class BigNumTest {
public static void main(String[] args) {
int[] a1 = new int[]{7, 9, 9};
int[] a2 = new int[]{1, 0, 0};
print(multi(a1, a2));
}
public static int[] multi(int[] ints, int[] ints2) {
int[] resultArr = new int[ints.length + ints2.length];
for (int i = 0; i < ints2.length; i++) {
int[] midArr = multiByNum(ints, ints2[i]);
if (ints2[i] != 0 && ints2.length - i - 1 > 0) {
// 添零 ints2.length-i-1
midArr = addZero(midArr, ints2.length - i - 1);
}
resultArr = add(resultArr, midArr);
}
reorder(resultArr);
return resultArr;
}
private static int[] addZero(int[] midArr, int count) {
int[] newArray = new int[midArr.length + count];
for (int i = 0; i < midArr.length; i++) {
newArray[i] = midArr[i];
}
return newArray;
}
private static int[] add(int[] ints, int[] ints2) {
return ints.length > ints2.length ? addDetail(ints, ints2) : addDetail(ints2, ints);
}
private static int[] addDetail(int[] ints, int[] ints2) {
int[] newArr = new int[ints.length];
for (int i = 0; i < ints.length; i++) {
newArr[ints.length - 1 - i] = i < ints2.length ? ints[ints.length - 1 - i] + ints2[ints2.length - 1 - i] : ints[ints.length - 1 - i];
}
return reorder(newArr);
}
private static int[] multiByNum(int[] ints, int num) {
int[] newArray = Arrays.copyOf(ints, ints.length);
for (int i = 0; i < ints.length; i++) {
newArray[i] = ints[i] * num;
}
reorder(newArray);
return newArray;
}
private static int[] reorder(int[] ints) {
// 进位与留位
for (int i = ints.length - 1; i > 0; i--) {
ints[i - 1] = ints[i - 1] + ints[i] / 10;
ints[i] = ints[i] % 10;
}
return ints;
}
private static void print(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i]);
}
System.out.println();
}
private static void printForHuman(int[] ints) {
boolean f = true;
for (int i = 0; i < ints.length; i++) {
if (ints[i] != 0) {
f = false;
}
if (f && ints[i] == 0) {
continue;
}
System.out.print(ints[i]);
}
System.out.println();
}
}
大数相乘-使用数组思路解决方案(Java版)
于 2020-05-18 02:30:10 首次发布