Python和Java编程题(六)

1.题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 
程序分析:采取逆向思维的方法,从后往前推断。

题目来源:http://blog.sina.com.cn/s/blog_60fafdda0100wb21.html

 

这题比较简单,只需从后往前逆推即可。程序可以通过循环,也可以通过递归实现。

 

Python代码实现

 1 # -*- coding: utf-8
 2 # 通过逆推计算桃子总数,循环实现
 3 def CalulatePeach(n, d):
 4     while d>0:
 5         n = (n + 1) * 2
 6         d = d - 1
 7     return n
 8 
 9 
10 if __name__ == '__main__':
11     LastPeachNumber = 1
12     LastDay = 10
13     SumPeach = CalulatePeach(LastPeachNumber, LastDay)
14     print("桃子的总数为:%d" % SumPeach)

 

Java代码实现

 1 public class MonkeyEatPeach {
 2     public void CalculatePeach(int n,int d) {
 3         for(int i=d;i>0;i--) {//循环逆推计算桃子总数
 4             n = (n + 1) * 2;
 5         }
 6         System.out.print(n);
 7     }
 8     
 9     public static void main(String args[]) {
10         MonkeyEatPeach monkey = new MonkeyEatPeach();
11         monkey.CalculatePeach(1, 10);//传入的参数为最后一天剩下的桃子数和总天数
12     }
13 }

 

posted @ 2018-09-25 20:58  埃克斯诶尔  阅读(205)  评论(0编辑  收藏  举报