力扣题目练习 换水问题

1

很简单,就是直到你剩余的空水瓶不足以换一瓶水的时候,就停止

复制代码
class Solution(object):
    #我有这么多水,exchange个瓶子可以兑换一瓶水
    def numWaterBottles(self, numBottles, numExchange):
        """
        :type numBottles: int
        :type numExchange: int
        :rtype: int
        """
        count=numBottles
        now_exchange=numBottles
        while (now_exchange//numExchange)>=1:
            count+=(now_exchange//numExchange)
            #现在有的空瓶子的数目
            now_exchange=(now_exchange%numExchange)+(now_exchange//numExchange)
        return count
solution=Solution()
result=solution.numWaterBottles(15,4)
print(result)

然后我们看加大难度的等级

题目的意思是这样的:空水瓶换水,一次只能换一瓶水,换完之后剩余的空水瓶数目仅仅+1,并且下一次换一瓶水需要的空水瓶数目还要涨,我这个没有思考其他方法,还是沿袭问题1的,代码如下:

复制代码
class Solution(object):
    #我有这么多水,exchange个瓶子可以兑换一瓶水
    #意思就是numexchange的数量是会发生改变的
    #而且一次只可以交换一个满水瓶
    def numWaterBottles(self, numBottles, numExchange):
        """
        :type numBottles: int
        :type numExchange: int
        :rtype: int
        """
        count=numBottles
        now_exchange=numBottles
        while (now_exchange//numExchange)>=1:
            count+=1
            #现在有的空瓶子的数目
            print(now_exchange)
            print('1',numExchange)
            now_exchange=(now_exchange%numExchange)+((now_exchange//numExchange)-1)*(numExchange)+1
            numExchange+=1
        return count
solution=Solution()
result=solution.numWaterBottles(10,3)
print(result)

但是其实每次只置换一瓶,就没必要这个除法了 那么条件就是如果剩余空水瓶数目大于等于置换一瓶水需要的空水瓶数目,便可以继续,所以我们可以写出更简单的代码

如果喜欢这个帖子,欢迎点赞收藏

相关推荐
Muyuan199814 分钟前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi
北顾笙98025 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
程序员-小李25 分钟前
uv 学习总结:从零到一掌握现代化 Python 工具链
python·学习·uv
m0_6294947326 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai30 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
Python大数据分析@33 分钟前
CLI一键采集,使用Python搭建TikTok电商爬虫Agent
开发语言·爬虫·python
研究点啥好呢39 分钟前
高德多模态算法工程师面试题精选:10道高频考题+答案解析
python·面试·llm·求职招聘·笔试·高德
旖-旎40 分钟前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
测试员周周1 小时前
【AI测试系统】第3篇:AI生成的测试用例太“水”?14年老兵:规则引擎+AI才是王炸组合
人工智能·python·测试
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法