如何将数组中的值从最后一个值添加到第一个值。

huangapple go评论76阅读模式
英文:

how to add values in an array from last value to first

问题

如何将arrNumbers中超过6的值相加,并将其添加到一个新数组中,新数组从最后一个值开始,以第一个值结束。

这是我编写的代码,但输出不正确。

    int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
    int[] newArrNumbers = new int[6];

    for (int i = arrNumbers.length - 1; i >= 0; i--) {
        if (arrNumbers[i] > 6) {
            newArrNumbers[5 - (arrNumbers.length - 1 - i)] += arrNumbers[i];
        }
    }

实际输出:

newArrNumbers = [1, 2, 3, 4, 7, 7]
英文:

How can I add the values in the arrNumbers that exceed 6 to add to a new array starting from the last value and ending at the first.

This is what I have written, but does not produce the right output.

    int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
    int[] newArrNumbers = new int[6];

    for(int i  = 0; i < arrNumbers.length ; i++){
        newArrNumbers[i % 6] += arrNumbers[i];
    }

The actual output:

newArrNumbers = [2, 4, 3, 4, 5, 6]

However, I want the output to ADD to the LAST VALUE in the arrNumbers, going from right to left, not left to right. So result should be:

newArrNumbers = [1, 2, 3, 4, 7, 7]

答案1

得分: 1

尝试一下。

int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
int[] newArrNumbers = new int[6];

for (int i = 0; i < arrNumbers.length; i++) {
    newArrNumbers[i < 6 ? i : (6 - (i % 6) - 1)] += arrNumbers[i];
}
System.out.println(Arrays.toString(newArrNumbers));

输出:

[1, 2, 3, 4, 7, 7]
英文:

Try this.

int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2 };
int[] newArrNumbers = new int[6];

for(int i  = 0; i &lt; arrNumbers.length ; i++){
    newArrNumbers[i &lt; 6 ? i : (6 - (i % 6) - 1)] += arrNumbers[i];
}
System.out.println(Arrays.toString(newArrNumbers));

output:

[1, 2, 3, 4, 7, 7]

huangapple
  • 本文由 发表于 2020年9月2日 16:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63701839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定