传统方法就是计算阶乘后
转化为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