题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
int counts=1;
for(int i=3,j=1;i<=n;i++){
int t=counts;
counts=j+counts;
j=t;
}
System.out.println(counts);
}
}
}
月份 n:兔子 数量counts
n=1: counts=1
n=2: counts=1
n=3: counts=2;
n=4: counts=3
n=5: counts=5;
n=6: counts=8
n: counts=counts(n-1)+counts(n-2)
从三月份开始 每个月新增的兔子的数量刚好等于上上个月的兔子数量,因为题目规定是兔子成长2个月就可以生小兔子。上上个月的兔子到这个月全部可以生小兔子。所以这个月的兔子数量等于上个月兔子 加 上上个月的兔子数量
