public static void main(String[] args) { System.out.println(buyWater(10)); } static int buyWater(int money){
//非递归 int count=money/2; int bo=count; int cap=count; while(bo>=2||cap>=4){ while(bo>=2){ count++; //换一瓶,获得一个瓶子,扣除两个瓶子 bo=bo+1-2; cap++; } while(cap>=4){ count++; //换一瓶,获得一个瓶盖,扣除4个瓶盖 cap=cap+1-4; bo++; } } return count; }
最后结果:15瓶
总结:要用while循环把瓶子盖子消耗完,单步调试发现,不够15瓶的情况都是没有消耗完瓶子盖子。
下面是递归方式:
int total=10/2; buyWater1(total,total,total);
static void buyWater1(int total,int c,int b){ //递归 int water=total,cap=c,bo=b; int newWater=cap/4+bo/2; cap=newWater+cap%4; bo=newWater+bo%2; water+=newWater; if(cap<4&&bo<2){ System.out.println(water); } else{ //传water是为了累加 buyWater1(water,cap,bo); } }