前言
经过前期的数据结构和算法学习,开始以OD机考题作为练习题,继续加强下熟练程度。
描述
有一种兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子。
例子:假设一只兔子第3个月出生,那么它第5个月开始会每个月生一只兔子。
一月的时候有一只兔子,假如兔子都不死,问第n个月的兔子总数为多少?
数据范围:输入满足 1≤𝑛≤31 1≤n≤31
输入描述:
输入一个int型整数表示第n个月
输出描述:
输出对应的兔子总数
示例1
输入:
3
输出:
2
实现原理与步骤
找寻对应月份兔子增加的规律。然后按规律编写代码即可。
月份,兔子增加个数
1,1
2,1
3,1,1 +1
4,1,1,1 +1
5,1,1,1,1,1 +2
6,1,1,1,1,1,1,1,1 +3
7,1,1,1,1,1,1,1,1,1,1,1,1,1 +5
8,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +8
实现代码
内存溢出版本,未能通过所有用例。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int month=in.nextInt();
int res=1;
int one=0;int two=0;int three=0;
for(int i=0;i<month;i++){
if(i>=2){
if(i==2){
three=1;
}else{
three=one+two;
}
res+=three;
one=two;
two=three;
}
}
System.out.println(res);
}
}