我从我的函数收到不一致的结果,它将减去32位不同长度的数组中的元素。它不是从两个数组的末尾开始,而是从第二个数组的开始处开始直到结束。我有点困惑,为什么,因为我的循环从最后开始。任何帮助将不胜感激。
int carry = 0;
int total = Math.max(tempArray.length, tempArrayTwo.length);
int[] subArray = new int[total];
for (int i = differenceArray.length - 1; i >= 0; i--) {
int first = i < tempArray.length ? tempArray[tempArray.length - i - 1] : 0;
int second = i >= tempArrayTwo.length ? 0 : tempTwoArray[tempTwoArray.length - i - 1];
int difference = first - second - carry;
carry = 0;
if (difference < 0) {
difference = difference + 10;
System.out.println(difference);
carry = 1;
}
subArray[subArray.length - 1 - i] = difference;
我遇到的问题是,数组1的大小为6,总数为46,数组2的大小为3(总数为24),减法将从第一个第24个字符的开头开始数组和第二个数组的第一个元素。
(at the 24th of 46 slot of array One)
00003333 33333333 33333333 array One
10000000 00000000 00000000 arrayTwo
它不是从arrayOne的3和arrayTwo的0开始,而是从arrayOne的0和arrayTwo的1开始。 很奇怪,特别是因为它有时会相应地起作用。 fyi表示较大阵列的额外数字。只是这些特殊的数字被搞砸了。
答案 0 :(得分:0)
您的问题是如何索引数组
int carry = 0;
int total = Math.max(tempArray.length, tempArrayTwo.length);
int[] subArray = new int[total];
//you want subArray below, not differenceArray
for (int i = subArray.length - 1; i >= 0; i--) {
int first = i < tempArray.length ? tempArray[tempArray.length - i - 1] : 0;
//Line above probably should just be int first = tempArray[i];
int second = i >= tempArrayTwo.length ? 0 : tempTwoArray[tempTwoArray.length - i - 1];
//Line above probably should just be int second = tempTwoArray[i];
int difference = first - second - carry;
carry = 0;
if (difference < 0) {
difference = difference + 10;
System.out.println(difference);
carry = 1;
}
subArray[subArray.length - 1 - i] = difference;