La cerveza cuesta dos yuanes por botella, dos botellas vacías por botella, cuatro tapas por botella
P: ¿Cuántas botellas puedo comprar por 10 yuanes?
Análisis: Después de comprar cerveza por primera vez, convierta las tapas y botellas que tiene en dinero y compre de forma recursiva.
public class BeerProblem {
public static int allBeerNum;//记录购买的啤酒总数
public static int lastPingZiNum;//记录瓶子剩余
public static int lastGaiZiNum;//记录盖子剩余
public static void main(String[] args) {
buyBeer(10);
System.out.println("可以买:"+allBeerNum+"瓶,剩余瓶子数:"+lastPingZiNum+",剩余盖子数:"+lastGaiZiNum);
}
public static void buyBeer(int money){
//购买啤酒
int number =money/2;
allBeerNum +=number;
//计算出当前拥有的瓶子盖子数
int currentPingZiNum = lastPingZiNum + number;
int currentGaiZiNum = lastGaiZiNum + number;
//将瓶子换成钱
int total =0;
total +=(currentPingZiNum/2)*2;
lastPingZiNum = currentPingZiNum %2;
//将盖子换成钱
total += (currentGaiZiNum/4)*2;
lastGaiZiNum =currentGaiZiNum % 4;
//拿瓶子和盖子换酒
if (total >=2)
buyBeer(total);
}
}