题目

你有 20 块钱,一瓶饮料卖 5 块钱,2个瓶身能够换一瓶饮料,4个瓶盖能够换一瓶饮料。问最多能够喝多少瓶饮料

思路

除了第一次用钱买,残余的均是通过瓶身或瓶盖兑换而来,那么兑换到直到瓶身和瓶盖无奈兑换为止

编码

function buyDrinks(total, price) {  //第一次用钱购买  const firstNum = Math.floor(total / price);  let res = firstNum;  // 残余瓶盖  let remainCap = firstNum;  // 残余瓶身  let remainBody = firstNum;  // 兑换  while(remainCap >= 4 || remainBody >= 2) {    // 瓶盖可兑换数量    const numCap = Math.floor(remainCap / 4);    // 瓶身可兑换数量    const numBody = Math.floor(remainBody / 2);    // 总共兑换的数量    const changeTotal = numCap + numBody;    res += changeTotal;    remainCap = remainCap % 4 + changeTotal;    remainBody = remainBody % 2 + changeTotal;  }    return res;} console.log(buyDrinks(20, 5))