其实就是递归知识的运用!下面是代码,
public static void main(String[] args) {
System.out.println(20+getNum(20));
}
public static int getNum(int money){
int sum = 0;
sum += (money / 2);
if(money>=2)
return sum+getNum(sum+money%2);
else
return 0;
}
运行下你就知道答案了!
public class test{
public static void main(String[] args) {
//1元1瓶的话,一共是20瓶
int num = 20;
//累加量,算出来就是2瓶空瓶兑换1瓶的总数
int temp = 0;
//2瓶空瓶换1瓶,应该就是每次都是总数除以2
while(num > 0){
temp += num;
num = num / 2;
}
System.out.println(temp);
}
}
输出答案应该是38
public class Test51 {
public static void main(String[] args) {
int money = 20; //定义总钱数为20
int price = 1; //定义单价为1
int num = money / price; //定义初始总瓶数
int bottle = num; //定义空瓶初始数量等于num
//定义一个方法,参数为总瓶数和目前的空瓶数量,返回值为矿泉水瓶数
int totalNum = getWaterNum(num , bottle);
System.out.println("共可喝到" + totalNum + "瓶水");
}
public static int getWaterNum(int num , int bottle) {
int tem ; //定义临时变量
if(bottle > 0) {//判断空瓶数量是否大于0
if(bottle % 2 == 0) { //如果剩余空瓶数量为偶数
tem = bottle / 2; //每两个空瓶可换一瓶水,可换tem瓶
num = num + tem; //将喝的总数加上tem瓶
bottle = tem;//此时空瓶数量变成了tem个
}else { //如果此时空瓶数量是奇数
bottle = bottle + 1; //就借一个空瓶
tem = bottle / 2; //可以换到tem瓶水
num = num + tem; //总数加上tem瓶
bottle = tem - 1; //还掉之前借的1个空瓶,此时空瓶数量为tem-1
}
return getWaterNum(num , bottle);//递归调用
}else {//当空瓶数量为0,返回总瓶数num
return num;
}
}
}