几道递归的经典习题

1.递归求N的阶乘

public static int fac(int num) {
        if(num == 1 ) {
            return num;
    }
    return num*fac(num-1);
    }
    public static void main(String[] args) {
        Scanner scan =new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(fac(num));
    }

2.递归求1+2+3+…+10

public static int sum(int num) {
    if(num == 1) {
        return num;
    }
    return num+sum(num-1);
    }
    public static void main(String[] args) {
        int num = 10;
        System.out.println(sum(num));
    }

3.按顺序打印一个数的每一位(例如1234打印出1 2 3 4)

public static void orderPrint(int num) {
        if(num > 9) {
            orderPrint(num/10);
        }
        System.out.println(num%10);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        orderPrint(num);
    }

4.写个递归方法,输入一个非负整数,返回组成它的数字之和

public static int sumNumber(int num) {
        if(num <10) {
            return (num%10);
        }
    return num%10+sumNumber(num/10);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(sumNumber(num));
    }

5.求菲波那契数列的第N项

public static int fibonacci1(int num) {
        if(num <= 2) {
            return 1;
        }
        return fibonacci1(num-1)+fibonacci1(num-2);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(fibonacci1(num));
    }

你可能感兴趣的:(几道递归的经典习题)