华为机试-统计每个月兔子的总数

问题描述

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

输入描述:
输入int型表示month

输出描述:
输出兔子总数int型

示例

示例1

输入 9
输出 34

解决思路

分析

问题的关键在找规律,直接看题目会以为是一道毫无规律的数学题,但是通过列举,会发现可循的规律。

方法

月份1个月2个月3个月总数
11001
20101
31012
41113
52125
63238

规律:个数=上两个月份之和(类似爬楼梯问题)
转换成公式:f(n) = f(n-1) + f(n-2),类似爬楼梯问题

  1. 通过递归实现
  2. 通过while循环实现

代码实现

// 思路1实现
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
            int a = in.nextInt();
            System.out.println(getRabbit2(a));
        }
    }
    
    public static int getRabbit(int month) {
        if (month <= 2) {
            return 1;
        }
        return getRabbit(month - 1) + getRabbit(month - 2);
    }
}
// 思路2实现
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
            int a = in.nextInt();
            System.out.println(getRabbit2(a));
        }
    }
    
    public static int getRabbit2(int month) {
        int one = 1;
        int two = 1;
        while (month > 2) {
            two = one + two; // 记录f(n) ==> f(n) = f(n-2) + f(n-1)
            one = two - one; // 记录f(n-1) ==> f(n-1) = f(n) - f(n-2)
            month--;
        }
        return two;
    }
}

小伙伴如果想测试的话,可以直接到牛客网这个链接做测试

华为机试-牛客网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值