题目: 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
递归:
public class Test{
public static void main(String[] args) {
System.out.println(getTotal(1));
}
public static int getTotal(int day){
if(day == 10){
return 1;
}
else{
return (getTotal(day+1)+1)*2;
}
}
}
循环:
public class Test{
public static void main(String[] args) {
int result = 1;
for(int i =1;i<10;i++){
result = (result+1)*2;
}
System.out.println(result);
}
}
运行结果:1534