递归应用-猴子吃桃问题(Java实现)

递归应用-猴子吃桃问题(Java实现)

题目描述:

有一群猴子摘了一堆桃子, 他们每天都吃当前桃子的一半且再多吃一个,到了第 10 天就只余下一个桃子。求出原来这群猴子共摘了多少个桃子。

实现代码:

public class RecursionExercise02 {
    public static void main(String[] args) {
        T2 t1 = new T2();
        int res = t1.monkeyeatpeach(1);
        if (res != -1) {
            System.out.println("the res is: " + res);
        }
        else {
            System.out.println("error");
        }
    }
}

class T2 {
    int monkeyeatpeach(int day) {
        if (day == 10) {
            return 1;
        }
        else if (day > 0) {
            //逆推法
        return (monkeyeatpeach(++day) + 1) * 2;
        } 
        else 
            return -1;           
    }

}

运行示例:

the res is: 1534

posted @ 2021-02-24 17:18  Irisx33  阅读(435)  评论(0)    收藏  举报