题目:初始给n瓶饮料,三个空瓶换一瓶饮料,请问最终可以喝多少饮料
public class Demo01 {
public static void main(String[] args) {
Drink drink = new Drink(80);
System.out.println(drink.drinkAndChange());
System.out.println(drinkAndChange(80, 0));
drinkAndChange(80);
}
// 递归写法
public static int drinkAndChange(int drink, int bottle) {
if (drink == 0 && bottle < 3) {
return drink;
} else {
return drink + drinkAndChange((drink + bottle) / 3, (drink + bottle) % 3);
}
}
// 非递归
public static void drinkAndChange(int n) {
int temp = n;
int count = 0;
while (true) {
temp -= 3;
temp++;
count++;
if (temp < 3) {
break;
}
}
System.out.println(n + count);
}
}
// 类的写法
class Drink {
int num;
int bottles = 0;
int drinked = 0;
public Drink(int num) {
this.num = num;
}
private void drinkAll() {
drinked += num;
bottles += num;
num = 0;
}
private void change() {
num += bottles / 3;
bottles %= 3;
}
public int drinkAndChange() {
while (num > 0 || bottles >= 3) {
if (num > 0) {
drinkAll();
}
if (bottles >= 3) {
change();
}
}
return drinked;
}
}
ps 没有考虑对n<0的判断
如有不对欢迎大家指正!