喝水问题
题目如下:假设有N瓶水(当然N>0吧)
每喝一瓶后可以得到的一个空瓶子
而 每3个空瓶子又能换1瓶水,喝掉以后又得到一个空瓶子,
问题是,你总共能喝多少瓶水,最后还剩余多少个空瓶子?
假设有1000瓶水:
//循环:
class Main{ public static void main(String[] args) { int emptybuttle = 0; int count = 0; for (int buttle = 1000; buttle != 0; buttle--) { emptybuttle++; count++; if (emptybuttle == 3){ emptybuttle = 0; buttle++; } } System.out.println("喝了"+count+"瓶水"+","+"还剩"+emptybuttle+"空瓶子"); } }
//递归:
class Main{ public static void main(String[] args) { drinkWater(1000,0,0); } public static int drinkWater(int buttle,int emptybuttle,int count){ if (buttle == 0 && emptybuttle <= 2){ System.out.println("喝了"+count+"瓶水"+","+"还剩"+emptybuttle+"空瓶子"); return count; } if (emptybuttle == 3){ emptybuttle = 0; buttle++; } return drinkWater(buttle-1,emptybuttle+1,count+1); } }