英文:
Find the sum of integers in a list (of type integers) recursively (java)
问题
我正在尝试编写一个方法,该方法返回整数类型列表中整数的和。目前我已经写出了以下代码:
public int sum(List<Integer> list) {
if (list.isEmpty()) {
return 0;
} else {
return sum(list.subList(0, list.size() - 1));
}
}
然而,这似乎并不起作用,代码中是否存在任何问题?任何帮助将不胜感激。
英文:
I am trying to write a method which returns the sum of integers in a list of type integer. This is what I have so far,
public int sum (List <Integer> list) {
if (list.isEmpty()) {
return 0;
}
else {
return sum(list.subList(0, list.size()-1));
}
}
However, this does not seem to work is there any problem with the code? Any help is appreciated.
答案1
得分: 2
你写成了sum([1,2,3,4]) = sum([1,2,3]),但实际上它等于(sum([1,2,3]) + 4)。
你的代码递归地计算了列表前缀的和,但没有加上最后一个元素的值。
英文:
You wrote sum([1,2,3,4]) = sum([1,2,3]) when in fact it is equal to (sum([1,2,3]) + 4).
Your code recursively computes the sum of the prefix of the list, but doesn't add the value of the last element.
答案2
得分: 0
public int sum(List<Integer> list) {
if (list.isEmpty()) {
return 0;
} else {
return list.get(list.size() - 1) + sum(list.subList(0, list.size() - 1));
}
}
I needed to sum the last value of the list as well, which is what
return list.get(list.size() - 1) + sum(list.subList(0, list.size() - 1));
achieves.
英文:
public int sum (List <Integer> list) {
if (list.isEmpty()) {
return 0;
}
else {
return list.get(list.size()-1) + sum(list.subList(0, list.size()-1));
}
}
I needed to sum the last value of the list aswell, which is what
return list.get(list.size()-1) + sum(list.subList(0, list.size()-1));
achieves.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论