Leetcode刷题记录——172. 阶乘后的零

在这里插入图片描述
传统方法就是计算阶乘后
转化为str 然后数0的个数
但是当n很大时,会超出时间限制
于是又到了大家最擅长的找规律时间
最后发现
对于输入的数字n
我们先找比它小的 最大的 5的m次幂
如 输入n=200,则比200小的 最大的 5的m次幂为5^3 = 125
找到后,我们求
res = (n//1) + (n//2) + … + (n//m)
即为所求
以下为代码

class Solution:
    def trailingZeroes(self, n: int) -> int:
        five = 0
        while 5**(five) <= n:
            five += 1
        five -= 1#比n小的最大的5的N次方
        print(five)
        res = 0
        for i in range(1,five+1):
            res += (n // (5**i))
        return res

以下为笨方法的代码,不满足时间限制

class Solution:
    def trailingZeroes(self, n: int) -> int:
        res = 1
        while n > 1:
            res = res*n
            n -= 1
        tempstr = str(res)
        print(tempstr)
        suma = 0
        length = len(tempstr)
        for i in range(length-1,-1,-1):
            if tempstr[i] == '0':#0
                suma += 1
            else:
                break
        return suma
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值