Multiply Array Integer: Approach One
public static int[] multiplynew(int[] arr1, int[] arr2){
int len1 = arr1.length;
int len2 = arr2.length;
int len = len1 + len2;
int[][] arr = new int[len1][len1+len2];
for(int i=len2-1; i >= 0; i--){
int carry = 0;
int j=0;
for(j=len1-1; j >= 0; j--){
int shiftLeft = i + 1;
arr[i][j + shiftLeft] = (arr1[j]*arr2[i] + carry) %10;
carry = (arr1[j]*arr2[i]+carry) / 10;
}
arr[i][(i+1)+j] = carry;
}
int[] total = new int[len];
int carry = 0;
for(int j=len-1; j >= 0; j--){
int s=0;
for(int i=0; i < len2; i++){
s += arr[i][j];
}
total[j] = (s + carry) % 10;
carry = (s + carry)/10;
}
return total;
}
Multiply Array Integer: Approach Two
1. Integer multiplies one dim array
2. Shift array to the left
3. Sum column in two dim array
// {1, 2, 3} x 3
public static int[] multiArr(int[] arr, int n){
int len = arr.length;
int c = 0;
int[] ret = new int[len + 1];
int lret = len + 1;
for(int i = 0; i < len; i++){
int s = arr[len - 1 - i] * n + c;
ret[lret - 1 - i] = s % 10;
c = s / 10;
}
ret[0] = c;
return ret;
}
public static int[] sumColumn(int[][] arr){
int[] ret = new int[arr[0].length];
int c = 0;
for(int i = 0; i < arr[0].length; i++){
int rIx = arr[0].length - 1 - i;
int s = 0;
for(int j = 0; j < arr.length; j++){
s += arr[j][rIx];
}
ret[rIx] = (s + c) % 10;
c = (s + c) / 10;
}
ret[0] = c;
return ret;
}
/**
1 2 3
2 3
1 2 3 <- a
3
2
↑
b
*/
public static int[] multiLongInteger(int[] a, int[] b){
int len1 = a.length;
int len2 = b.length;
int[][] arr = new int[len2][len1 + len2];
int lena = len1 + len2;
for(int i = 0; i < len2; i++){
int[] c = multiArr(a, b[b.length - 1 - i]);
for(int j = 0; j < c.length; j++){
arr[i][lena - 1 - j - i] = c[c.length - 1 - j];
}
}
printArr2d(arr);
return sumColumn(arr);
}