猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不過癮,又多吃了一個,
第二天早上又將剩下的桃子吃掉一半,又多吃了一個。以後每天早上都吃前一天剩下的一半零一個。
到第13天早上想再吃時,見只剩下一個桃子了。求第一天共摘多少個桃子?
方法一:常規for循環+數組的簡單應用
AC代碼:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] peach = new int[13];
peach[12] = 1; //第13天剩下一個桃子
for(int i=11;i>=0;i--){
peach[i] = (peach[i+1]+1)*2;
}
System.out.print("第一天一共摘了"+peach[0]+"個桃子");
}
}
方法二:遞歸思想
分析
- 13天1 12天4 11天10 10天22
- 12天的個數= 13天的個數*2+2
- 11天的個數= 12天的個數*2+2
- 把第13天當作第一天
AC代碼:
public class Main {
public static int eat(int day){
if(day==1){
return 1;
}else {
return eat(day-1)*2+2;
}
}
public static void main(String[] args) {
System.out.print(eat(13));
}
}