英文:
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();
}
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论