题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
import java.util.Objects;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String nextLine = in.nextLine();
if (Objects.isNull(nextLine) || nextLine.equals("")) {
break;
}
/**
* 有一种兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子。
* 例子:假设一只兔子第3个月出生,那么它第5个月开始会每个月生一只兔子。
* 一月的时候有一只兔子,假如兔子都不死,问第n个月的兔子总数为多少?
*
* 主要是读懂题,题目表述不清楚,出题人语文水平不好。
* 1、1月的这一只兔子 只有1个月大。
* 2、只要兔子长到三个月大的时候,就会马上怀孕生出一只有1个月大的兔子
* 3、循环数组里面的数据,计算即可
*/
int n = Integer.parseInt(nextLine);
int[] ints = new int[4];
ints[1] = 1;
ints[2] = 0;
ints[3] = 0;
for (int i = 2; i <= n; i++) {
calc(ints);
}
System.out.println(ints[1] + ints[2] + ints[3]);
}
}
public static void calc(int[] ints) {
int lastN1 = ints[1];
int lastN2 = ints[2];
int lastN3 = ints[3];
// 每计算一次,就会产生之前2月+3月之和的1个月大的兔子
ints[1] = lastN3 + lastN2;
// 把之前1月大的兔子丢进来
ints[2] = lastN1;
// 累计之前3月大的兔子和2月大的兔子
ints[3] = ints[3] + lastN2;
}
}
