给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5 输出: 1 解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
python3 这个程序出现超出时间限制,报错
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
if n==0:
return 0
def iter(n):#迭代求阶乘
if n==1:
return 1
if n>=2:
return n*iter(n-1)
res=iter(n)
count=0
for i in range(len(str(res))):
if res%10==0:
count+=1
res=res/10
return count
python3另一种解法
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
#每出现一次5的倍数时尾数加一个0
if n==0:
return 0
else:
return int(n/5)+int(self.trailingZeroes(n/5))
