leetcode172 python阶乘后的零

该博客探讨了如何在Python中有效地计算阶乘结果末尾的零数,针对LeetCode上的问题172。文章提到了遇到的时间限制问题以及两种不同的Python解题策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个整数 n,返回 n! 结果尾数中零的数量。

示例 1:

输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:

输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.

说明: 你算法的时间复杂度应为 O(log n) 

python3 这个程序出现超出时间限制,报错

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n==0:
            return 0
        
        def iter(n):#迭代求阶乘
            if n==1:
                return 1
            if n>=2:
                return n*iter(n-1)
            
        res=iter(n)
        count=0
        for i in range(len(str(res))):
            if res%10==0:
                count+=1
                res=res/10
        return count
        

python3另一种解法

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        #每出现一次5的倍数时尾数加一个0
        if n==0:
            return 0
        else:
            return int(n/5)+int(self.trailingZeroes(n/5))
        



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值