记得小时候一直在琢磨的问题, 拿空酒瓶(也有可能是可乐)换酒瓶, 最后面一共可以喝几瓶. 今天在 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
强烈推荐
- 英国代购-畅购英伦
- TopCashBack 返现 (英国购物必备, 积少成多, 我2年来一共得了3000多英镑)
- Quidco 返现 (也是很不错的英国返现网站, 返现率高)
- 注册就送10美元, 免费使用2个月的 DigitalOcean 云主机(性价比超高, 每月只需5美元)
- 注册就送10美元, 免费使用4个月的 Vultr 云主机(性价比超高, 每月只需2.5美元)
- 注册就送10美元, 免费使用2个月的 阿里 云主机(性价比超高, 每月只需4.5美元)
- 注册就送20美元, 免费使用4个月的 Linode 云主机(性价比超高, 每月只需5美元) (折扣码: PodCastInit2022)
- PlusNet 英国光纤(超快, 超划算! 用户名 doctorlai)
- 刷了美国运通信用卡一年得到的积分 换了 485英镑
- 注册就送50英镑 – 英国最便宜最划算的电气提供商
- 能把比特币莱特币变现的银行卡! 不需要手续费就可以把虚拟货币法币兑换
微信公众号: 小赖子的英国生活和资讯 JustYYUK