记得小时候一直在琢磨的问题, 拿空酒瓶(也有可能是可乐)换酒瓶, 最后面一共可以喝几瓶. 今天在 leetcode 看到了这题, 1518.
这题是简单题, 我们通过模拟就能解决. 需要的定义的变量就是总喝的瓶数, 还有就是当前空瓶数. 只要空瓶子够换新酒瓶, 我们就不停的循环这个过程. 需要注意的是新的空瓶数得把原来不够换的那部分也加上. 比如3个空瓶可以换一个新瓶, 现在有5个空瓶, 只够换1个, 然后新的空瓶就是(5-3+1=3)还够换1瓶. 不啰嗦了, 以下就是 Python代码.
1 2 3 4 5 6 7 8 9 | class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles empty = numBottles while empty >= numExchange: newBottles = empty // numExchange ans += newBottles empty = newBottles + empty % numExchange return ans |
class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles empty = numBottles while empty >= numExchange: newBottles = empty // numExchange ans += newBottles empty = newBottles + empty % numExchange return ans
英文: Simulation Algorithm to Compute the Number of Water Bottles
GD Star Rating
loading...
本文一共 178 个汉字, 你数一下对不对.loading...
上一篇: Github 开通了个人主页介绍和高光功能
下一篇: 在 速卖通 Ali Express 上的购物体验 (阿里巴巴国际版的几个坑)
扫描二维码,分享本文到微信朋友圈