【Java习题程序】递归类习题

斐波那契数列``:1 1 2 3 5 8 13 21 34…当前数是前两项数之和

递归求斐波那契数列第n项

public class Main {
    public static int fac(int n){
        if (n<=2){
            return 1;
        }
        return fac(n-1)+fac(n-2);
    }

    public static void main(String[] args) {
        System.out.println(fac(7));
    }

输出·结果
13

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

public static int sum(int n){
    if (n<9){
        return n;
    }
    return n%10+sum(n/10);``
}

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

public static void  find(int n){
    if (n>9){
         find(n/10);
    }
    System.out.print(n%10+" ");
}

public static void main(String[] args) {
   find(1234);
}

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

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

运行结果 55

递归求 N 的阶乘

public static int fac2(int n){
    if (n==1){
        return  1;
    }
    int tmp=0;
    tmp=n*fac2(n-1);
    return tmp;
}

public static void main(String[] args) {
    System.out.println(fac2(5));
}

运行结果 120

递归实现汉诺塔

public class TestDemo {
    /*
    n:盘子个数
    pos1:起始位置
    pos2:中间位置
    pos3:目标位置
     */
    public static void move(char pos1,char pos2){
        System.out.print(pos1+"->"+pos2+" ");
    }
    public static void hanota(int n,char pos1,char pos2,char pos3){
        if (n==1){
            move(pos1,pos3);
            return;
        }else{
            hanota(n-1,pos1,pos3,pos2);
            move(pos1,pos3);
            hanota(n-1,pos2,pos1,pos3);
        }
    }
    public static void main(String[] args) {
    //测试
        hanota(1,'A','B','C');
        System.out.println();
        hanota(2,'A','B','C');
        System.out.println();
        hanota(3,'A','B','C');
        System.out.println();
    }
}

运行结果
在这里插入图片描述

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

we_opkn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值