我用的递推求阶乘,str.count('0')的方法计算。但超过题目要求的O(log n)了。
所以, 最后这道题是到数学题,因式分解。。。数学推导过程
只要5和一个偶数相乘,结果就有一个0,那每两个5的倍数之间肯定有偶数(5-10中间肯定有偶数吧),所以偶数不需要考虑了,而且偶数的数量肯定比5的数量多吧(现在一个男生和一个女生能结婚,但是现在有20个男生 和 10个女生,你要去算能有多少对人结婚,你肯定只用考虑女生的数量啊),只需要考虑能有多少个5。5的阶乘就一个5 ,10的阶乘有2个5,100的阶乘:先100//5,有20个:然后除5得到20, 那个20还有4个5, 所以一共有24个。
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
r = 0
while n >= 5:
n = n // 5
r += n
return r
顺便复习一下,常规求阶乘。
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
result = n
for i in range(1,n):
result *= i
count_0 = 0
num = str(result)
num = num[::-1]
# print(num)
for i in range(len(num)):
if num[i] == '0':
count_0 += 1
else:
return count_0
# def factorial(self,n):
# if n==1:
# return 1
# else:
# return n*factorial(n-1)