啤酒问题:
12块钱买啤酒,2块钱一瓶
两个空瓶换一瓶酒
四个瓶盖换一瓶酒
最后能买多少啤酒?
问题:统一换算成钱,再买酒,递归实现
package cn.edu.lcudcc; public class BeerQuestion { // 定义一个静态的成员变量用于存储可以买的酒数量 public static int totalNumber; // 总数量 public static int lastBottleNumber; // 记录每次剩余的瓶子个数 public static int lastCoverNumber; // 记录每次剩余的盖子个数 public static void main(String[] args) { int money = 12; buy(money); System.out.println("totalNumber = " + totalNumber); System.out.println("lastBottleNumber = " + lastBottleNumber); System.out.println("lastCoverNumber = " + lastCoverNumber); } /** * 拿钱买酒 * @param money */ private static void buy(int money) { int buyNumber = money / 2; totalNumber += buyNumber; int coverNumber = lastCoverNumber + buyNumber; int bottleNumber = lastBottleNumber + buyNumber; int allMoney = 0; if(coverNumber >= 4) { allMoney += (coverNumber / 4) * 2; } lastCoverNumber = coverNumber % 4; if (bottleNumber >= 2){ allMoney += (bottleNumber / 2) * 2; } lastBottleNumber = bottleNumber % 2; if(allMoney >= 2) { buy(allMoney); } } }
输出结果:
totalNumber = 19 lastBottleNumber = 1 lastCoverNumber = 3
标签:lastCoverNumber,Java,int,money,lastBottleNumber,问题,static,totalNumber,啤酒 From: https://www.cnblogs.com/zhzhang/p/16990598.html