小编Blu*_*Ree的帖子

Java - 理解递归

有人可以向我解释为什么打印1 2 3 4 5?我想它会打印4 3 2 1 0但我的书和日食都说我错了.

public class whatever {

    /**
     * @param args
     */
    public static void main(String[] args) {
        xMethod(5);

    }

    public static void xMethod(int n){
        if (n>0){
            xMethod(n-1);
            System.out.print(n + " ");
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

java recursion

6
推荐指数
2
解决办法
9002
查看次数

这是尾递归吗?

我试图找到尾递归的例子,我真的没有看到常规和尾部之间的区别.如果这不是尾递归,有人可以告诉我为什么不是?

public static long fib(long index) {

// assume index >= 0

if (index == 0) // Base case

  return 0;

else

  if (index == 1) // Base case

    return 1;

  else

    // Reduction and recursive calls

    return fib(index - 1) + fib(index - 2);

}  // end of method fib(long index)
Run Code Online (Sandbox Code Playgroud)

java recursion computer-science tail-recursion fibonacci

4
推荐指数
1
解决办法
5518
查看次数