JAVA:使用递归从头到尾添加

时间:2017-03-03 17:57:39

标签: java recursion

我需要这个递归方法的帮助。我需要它从起点到终点添加整数。

    public static int sumInts(int begin, int end){
    if (begin == end)
        return begin + end;
    else
        return sumInts(begin+1,end);
}

示例输出应该是: Start: 1 End: 4 Sum is: 10

但是我得到了8作为这些特定输入的输出。我知道这是毁了这个的条件,但我似乎无法解决这个问题。

1 个答案:

答案 0 :(得分:7)

  

但是我得到了8作为这些特定输入的输出。

这很正常。每次都会转到else块,但最后一次,因为beginend都是4,它将返回4 + 4 = 8

你应该这样做:

public static int sumInts(int begin, int end){
    if (begin == end)
        return end; // return the last number
    else
        return begin + sumInts(begin+1,end); // sum the current number with the recursion result
}

当然,这可以通过其他方式完成 - 减少end而不是增加begin

public static int sumInts(int begin, int end){
    if (begin == end)
        return begin;
    else
        return end + sumInts(begin,end-1);
}