JAVA单排日记-2020/1/22-递归

  • 分类:
  • 直接递归:方法自己调用自己
  • 间接递归:a调用b,b再调用a
  • 注意:
  • 要有条件限定,确保递归能够停止
  • 次数不能太多
  • 构造方法禁止递归
  • 练习

在这里插入图片描述

package Recurrence;

public class Demo01 {
    public static void main(String[] args) {

        System.out.println(sum(10));
    }

    public static int sum(int n) {
        if (n==1){
            return 1;
        }
        return  n+sum(n-1);
    }
}

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

package Recurrence;

public class Demo02 {
    public static void main(String[] args) {

        int f= factorial(5);
        System.out.println(f);
    }

    public static int factorial(int n){
        if (n==1){
            return 1;
        }
        return n*factorial(n-1);
    }
}

在这里插入图片描述

发布了95 篇原创文章 · 获赞 1 · 访问量 2250

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104071550