题目:1518. Water Bottles
描述:Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Return the maximum number of water bottles you can drink.
Example 1:
Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Number of water bottles you can drink: 9 + 3 + 1 = 13.
Example 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.
Example 3:
Input: numBottles = 5, numExchange = 5
Output: 6
Example 4:
Input: numBottles = 2, numExchange = 3
Output: 2
Constraints:
1 <= numBottles <= 100
2 <= numExchange <= 100
来源:力扣(LeetCode)
分析:题目大意就是你买了numBottles瓶酒,规定每numExchange个空瓶可以兑换一瓶酒,计算对多可以喝到多少瓶酒。
比如在示例一中,我买了9瓶酒,每三个空瓶可以兑换一瓶酒,第一次全部喝完可以兑换9/3=3瓶酒,第二次喝完三瓶酒又可以刚好兑换一瓶酒,所以最多能喝到的酒一共有9+3+1=13瓶。
**解法一:**根据题意,可以比较容易的找到其中的数学计算关系,无非就是一系列的累加作除取余,代码有些注释,这里不再赘述:
public static int WaterBottles(int numBottles,int numExchange){
if (numBottles / numExchange == 0){
return numBottles;//若所有瓶子小于交换要求,直接return所有瓶子数即可
}
int nowBottles = numBottles;//目前所拥有的非空瓶数
int tempBottles = numBottles;//交换变量,
int surplusBottles = nowBottles % numExchange;//变量:存储每次交换后的余数的值
while (tempBottles>=numExchange){
surplusBottles = tempBottles % numExchange;
nowBottles+=tempBottles/numExchange;
tempBottles = tempBottles/numExchange + surplusBottles;// tempBottles = 每次换来的空瓶数+刚好换完后剩下的空瓶数
}
return nowBottles;//最终返回所拥有的瓶数
}
**解法二:**看了三个示例之后,我第一反应是想能不能找一下其中的规律,方便简化代码量,无奈最终误解,解法一AC之后,借鉴了一下其他大佬的解法,终于找到了最短代码的解法,果然大佬思路清奇啊!
解法二大致是这样的,我们假设一个空瓶价值为1的话,那么
numBottles * numExchange
为总价值。又因为题目要求:
1 <= numBottles <= 100
2 <= numExchange <= 100那么
至少一个空瓶无论如何是兑换不了的,所以总价值-1,
numExchange-1
为一瓶酒的价值,。如此一来,问题就变得简单了许多,直接总价值/每一瓶酒的价值就是该情况最多可以喝到的酒的瓶数了!!!(向大佬致敬!)
public static int waterBottles(int numBottles,int numExchange) {
return ((numBottles * numExchange) - 1) / (numExchange - 1);
}
更多解法有待研究---------完美的结束线-------------------------------