統計每月兔子的總數

題目描述

有一對兔子,從出生後第3個月起每月都生一對兔子,小兔子長到第三個月後每月又生一對兔子,假如兔子都不死,問每月的兔子總數爲多少?

/**
 * 統計出兔子總數。
 * 
 * @param monthCount 第幾個月
 * @return 兔子總數
 */
public static int getTotalCount(int monthCount) {
    return 0;
}

輸入描述

輸入int型表示month

輸出描述

輸出兔子總數int型

輸入例子

9

輸出例子

34

解題思路

這裏寫圖片描述

算法實現

import java.util.Scanner;

/**
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            int input = scanner.nextInt();
            System.out.println(countRabbit(input));
        }

        scanner.close();
    }

    /**
     * 統計第n個月的兔子總數
     * 兔子能夠看做第一個月未成熟,第二個月成熟,第三個月產仔,能夠構造一個「斐波那契數列」問題
     *
     * @param input
     * @return
     */
    private static int countRabbit(int input) {

        if (input <= 0) {
            return 0;
        } else if (input <= 2) {
            return 1;
        } else {

            int prev1 = 1;
            int prev2 = 1;
            int result = 0;
            for (int i = 3; i <= input; i++) {
                result = prev1 + prev2;
                prev1 = prev2;
                prev2 = result;
            }
            return result;
        }
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息
相關文章