寻找整数列表(整数类型)中整数的递归求和(Java)

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

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 &lt;Integer&gt; 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 &lt;Integer&gt; 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.

huangapple
  • 本文由 发表于 2020年4月5日 06:23:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61035577.html
匿名

发表评论

匿名网友

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

确定