1、第一种PHP实现
public function test()
{
$money = input('money') ?? 10; //总价
if ($money < 2) {
echo 1;
exit();
}
//计算第一次的
$num = intval($money / 2); //总数量
$capNum = $num; //瓶盖数量
$bottleNum = $num; //剩余空瓶数量
//开始兑换
while ($capNum >= 4 || $bottleNum >= 2) {
if ($capNum >= 4) {
$newNum = intval($capNum / 4); //计算兑换多少瓶
$capNum = $capNum % 4;//剩余多少瓶盖
$num += $newNum; //总数量+
$capNum += $newNum;//瓶盖数量
$bottleNum += $newNum; //空瓶数量+
}
if ($bottleNum >= 2) {
$newNum = intval($bottleNum / 2); //计算兑换多少瓶;
$bottleNum = $bottleNum % 2; //剩余多少空瓶
$num += $newNum; //总数量+
$bottleNum += $newNum;//空瓶数量
$capNum += $newNum; //瓶盖数量
}
}
echo $num;
}
2、第二种PHP实现
/**
* 计算啤酒数量
* @param money 金额
* @param unitPrice 每瓶酒单价
* @param capRule 瓶盖兑换规则
* @param bottelRule 瓶子规则兑换
* @return
*/
public static int calculationBeerAmount(int money,int unitPrice,int capRule,int bottelRule){
int beer = money / unitPrice;//初始的啤酒数
int bottel = beer;//初始的瓶子数
int cap = beer;//初始的瓶盖数
int temp;
while (cap >= capRule || bottel >= bottelRule) {
if ((temp = cap / capRule) > 0) {
beer = beer + temp;
cap = cap - capRule * temp + temp;
bottel = bottel + temp;
}
if ((temp = bottel / bottelRule) > 0) {
beer = beer + temp;
cap = cap + temp;
bottel = bottel - bottelRule * temp + temp;
}
}
return beer;
}
3、JS实现
var flag = true;
var number = 5; //总数量
var emptyBottle = 5; //空瓶数量
var cap = 5; //瓶盖数量
while (flag) {
console.log("emptyBottle:" + emptyBottle, "cap:" + cap)
if (emptyBottle < 2 && cap < 4) {
flag = false;
}
if (emptyBottle >= 2) {
number = number + parseInt(emptyBottle / 2);
cap = cap + parseInt(emptyBottle / 2);
emptyBottle = emptyBottle % 2 + parseInt(emptyBottle / 2);
}
if (cap >= 4) {
number = number + parseInt(cap / 4);
emptyBottle = emptyBottle + parseInt(cap / 4);
cap = cap % 4 + parseInt(cap / 4);
}
}
console.log(number)