将数组值与它们的数字相加,如21+9 = 30
. 当9+1=10
十位值被借用并添加到十位时。在哪里形成 java 8 结果是21+9 = 210
.
Array 1 + Array 2 = Reslut Array ~ Java8 Result
{0, 1, 2} + {3, 4, 9} = [0, 3, 6, 1] ~ [3, 5, 11]
{0, 1, 2, 1} + {3, 4, 9} = [0, 0, 4, 7, 0] ~ [3, 5, 11, 1]
将所有两个数组值转换为单个数组的简单 java 逻辑:
注意:第一个数组的长度必须大于第二个数组的长度。
public static int[] arraysAddition_Int(int[] a1, int[] a2) {
int borrowing = 0;
int[] resultArr = new int[a1.length+1];
for (int i = a1.length - 1, j = a2.length - 1; i >= 0; i--, j--) {
int n1 = a1[i];
int n2 = 0;
if (j >= 0) {
n2 = a2[j];
}
int temp = n1 + n2 + borrowing;
borrowing = 0; // After adding make it as ZERO.
if (temp > 9) {
borrowing = 1;
temp -= 10;
}
resultArr[i+1] = temp;
}
if (borrowing > 0) {
resultArr[0] = borrowing;
}
System.out.format("[%s + %s]=[%s]\n --- \n",
Arrays.toString(a1), Arrays.toString(a2), Arrays.toString(resultArr));
return resultArr;
}
使用 Java 8:
private static int[] arraysAddition_java8(int[] a, int b[]) {
int startInclusive = 0, endExclusive = Math.max(a.length, b.length);
IntUnaryOperator mapper = index -> (index < a.length ? a[index] : 0) + (index < b.length ? b[index] : 0);
return IntStream.range(startInclusive, endExclusive).map(mapper).toArray();
}