如何在Java中从一个数字列表中减去另一个数字列表,直到结果为0。

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

How to substract a list of numbers from another list of numbers until 0 in java

问题

I have 2 lists of numbers. I need to subtract the second list from the first in a way that shows the balance until the first list equals 0.

For example:

List A = [10,9]
List B - [1,2,3,4,5,4]

I need to show:

10-1=9
9-2=7
7-3=4
4-4=0
9-5=4
4-4=0

I tried:

for (int a : List A){
do {
for (int b : List B){
a = -b
}
} while (a >= 0)
}

I don't think the logic is sound enough and could use a few pointers.

英文:

I have 2 lists of numbers. I need to subtract the second list from the first in a way that shows the balance until the first list equals 0.
For example

List A = [10,9] 
List B - [1,2,3,4,5,4]

I need to show

10-1=9
9-2=7
7-3=4
4-4=0
9-5=4
4-4=0

I tried

 for (int a : List A){
        do {
            for (int b : List B){
                a = -b
            }
        } while (a >= 0)
    }

I don't think the logic is sound enough and could use a few pointers.

答案1

得分: 1

你可以在从所有B元素中减去之前,如果a在减法运算之前变为0,可以使用提前中断来简化逻辑。此外,看起来你希望在a变为0之前以循环的方式减去它们。

代码段:

for(int a : A){
    int ptr = 0;
    while(a > 0){
        System.out.println(a + " - " + B.get(ptr) + " = " + (a - B.get(ptr)));
        a -= B.get(ptr);
        ptr = (ptr + 1) % B.size();
    }
}

在线演示

注意: 并非每个元素的减法都会导致最终为0,但这就是你的数组一开始就保持的方式。

根据你当前的要求,看起来没有其他更优化的方法,因为你必须遍历每个元素并显示减法步骤。

英文:

You can make your logic more simpler with early breaks if a becomes 0 before subtracting from all elements in B. Also, it looks like you wish to subtract them in a circular manner until a becomes 0.

Snippet:

for(int a : A){
    int ptr = 0;
    while(a > 0){
        System.out.println(a + " - " + B.get(ptr) + " = " + (a - B.get(ptr)));
        a -= B.get(ptr);
        ptr = (ptr + 1) % B.size();
    }
}

Online Demo

Note: Not every element subtraction leads to the beautiful 0, but that is how your array is kept in the first place.

Also, there is no other optimized way looking at your current requirements since you will have to loop through each one and show the subtraction steps.

huangapple
  • 本文由 发表于 2023年2月10日 07:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75405591.html
匿名

发表评论

匿名网友

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

确定