原题:
一只猴子收到一筐香蕉,猴子每天吃了筐中的一半香蕉后,又多吃了一个,直到第10天,这筐香蕉刚好吃完,请写段代码计算出这筐香蕉最初有几个。
解题思路:
首先就像做数学题一样,获取题目中重要的信息。
思考一下,猴子在第10天的时候筐中的香蕉数量是几个才能刚好吃完?
2/2 - 1 = 0,所以第10天香蕉的数量一定是2个的时候,猴子才能刚好吃完。
所以:
// 第10天吃的香蕉数量一定是2个 // 第9天的香蕉数量是6个 // 第8天的香蕉数量是14个 // 第7天的香蕉数量是30个 // 第6天的香蕉数量是62个 // 规律出来了 n*2 + 2
代码实现:
package com.xieh; public class Demo{ public static void main(String[] args) { // 第10天吃的香蕉数量一定是2个 // 第9天的香蕉数量是6个 // 第8天的香蕉数量是14个 // 第7天的香蕉数量是30个 // 第6天的香蕉数量是62个 // 规律出来了 n*2 + 2 int day = 10; int banana = 0; for (int i = 1; i <= day; i++) { banana = banana*2 + 2; } System.out.println("香蕉最初有:" + banana); } }
香蕉最初有:2046