Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
不得不说这道题太经典,因为它逼着你去优化
算一个数的阶乘,结尾有多少0
小学奥数,就是算因子2和5有多少个
而2肯定比5多,所以只需要算5有多少个
最开始是对每个数,除以五那样算,到一个很大的数的时候,超时了
这样就得想怎么优化。
对一个数n,它肯定有 n/5 个5,
这样没数全,还得看25,125……等等
所以,直接优化成这样
</pre></div><div><span style="font-size: 14px;"><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"><span style="color: rgb(51, 51, 51);"></span></span></span><pre name="code" class="html"><span style="white-space:pre"> </span>num_5 = 0
while n>0:
n /= 5
num_5 += n
后来发现可以递归:
return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)
class Solution(object):
def trailingZeroes(self, n):
#return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)
num_5 = 0
while n>0:
n /= 5
num_5 += n
'''
for i in xrange(1,n+1):
#print i,
while i > 1 and i % 5 == 0:
if i!= 0:
num_5 += 1
i /= 5
'''
return num_5
"""
:type n: int
:rtype: int
"""