面试,递归:买汽水,1块钱可以买1瓶汽水,2个空瓶可以换一瓶汽水,3个瓶盖可以换一瓶汽水,问:20块可以买到多少瓶汽水



public class Drink {

public static void main(String[] args) {
int drink = 20;
int bottle = 20;

int cap = 20;

//把参数定义为成员变量

System.out.println(getMax(bottle, cap, drink));
}


public static int getMax(int bottle, int cap, int drink) {
if (bottle < 2 && cap < 3) {
return drink;

}

//此处一定要加一个变量num

int num = cap / 3 + bottle / 2;
drink += num;
bottle = num + bottle % 2;

cap = num + cap % 3;

//进行递归

return getMax(bottle, cap, drink);
}

}

你可能感兴趣的:(面试,递归:买汽水,1块钱可以买1瓶汽水,2个空瓶可以换一瓶汽水,3个瓶盖可以换一瓶汽水,问:20块可以买到多少瓶汽水)