題目連結(https://leetcode.com/problems/water-bottles/description/?envType=daily-question&envId=2025-10-01)
There are numBottles
water bottles that are initially full of water. You can exchange numExchange
empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles
and numExchange
, return the maximum number of water bottles you can drink.
每日一題,數學題,有關商和餘數的處理與模擬
numBottles
, 兌換比例numExchange
1 <= numBottles <= 100
2 <= numExchange <= 100
原本有 15 個滿瓶,4 個空瓶可換 1 個滿瓶
15/4 = 3…2 ,15 個空瓶可換 3 個滿瓶,剩下 2 個空瓶
q=3, c=2,3 個滿瓶喝完變 3 個空瓶 加上 2 個空瓶
(2+3) /4 =1…1,5 個空瓶可換 1 個滿瓶,剩下 1 個空瓶
q=1, c=1
(1+1)/4 = 0…2,換不了,剩下 2 個空瓶
Input: numBottles = 15, numExchange = 4
Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 15 + 3 + 1 = 19.
模擬一個重複的兌換過程直到無法兌換為止。由於兌換過程每次會消耗 numExchange 個空瓶,並產生 1 個滿瓶,我們可以持續利用長除法來計算能兌換的次數。
class Solution {
public:
int numWaterBottles(int numBottles, int numExchange) {
int q = numBottles / numExchange; // 第一次換到的滿瓶數(商)
int r = numBottles % numExchange; // 第一次剩下的空瓶數(餘)
int result = numBottles + q; // 總共喝掉 = 初始 + 第一次換到的
while (q + r >= numExchange) {
int empty = (q + r); // q 是「新喝完的瓶」,c 是「剩下的空瓶」
q = empty / numExchange; // 再次兌換
r = empty % numExchange; // 再次剩餘
result += q;
}
return result;
}
};
ps. 部分內容經 AI 協助整理