172. 階乘後的零
阿新 • • 發佈:2018-12-17
我用的遞推求階乘,str.count('0')的方法計算。但超過題目要求的O(log n)了。
所以, 最後這道題是到數學題,因式分解。。。數學推導過程
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)