汽水瓶问题
喝汽水,1瓶汽水1元,2个空瓶可以换1瓶汽水,给20元,可以换多少汽水。
每次喝的汽水瓶数等于前面喝的瓶数加上总数的一半再加上总数模2的数
| 元(瓶)兑换 | 剩下空瓶 | 换得 |
1 | 20 | 0 | 10 |
2 | 10 | 0 | 5 |
3 | 5 | 1 | 2 |
4 | 2 | 0 | 1 |
5 | 1 | 1 | 1(两次空瓶可换一次) |
class Drink { public static void main(String[] args) { System.out.println(drink(20, 0)); } public static int drink(int money, int bottle) { int empty = money + bottle; if (empty / 2 == 0) { return money; } return money + drink(empty / 2, empty % 2); } }
进阶版
1瓶汽水1元,2个空瓶换1瓶汽水,3个瓶盖换一瓶汽水,给20元,可以换多少汽水。
class Drink { public static void main(String[] args) { System.out.println(drink(20, 0, 0)); } private static int drink(int money, int bottle, int cap) { bottle = money + bottle; cap = money + cap; if (bottle / 2 + cap / 3 == 0) { return money; } return money + drink(bottle / 2 + cap / 3, bottle % 2, cap % 3); } }