2. 尾部的零 设计一个算法,计算出n阶乘中尾部零的个数 样例 11! = 39916800,因此应该返回 2 挑战 O(logN)的时间复杂度
使用python设计,但是时间复杂度达不到。
class Solution:
"""
@param: n: An integer
@return: An integer, denote the number of trailing zeros in n!
"""
def trailingZeros(self, n):
# write your code here, try to do it without arithmetic operators.
i=0
t=0
while(i<=n):
#long(b)
if i==0 :
b=1
i=i+5
else :
i=i+5
h=i
while((h%5)==0) :
h=h/5
t+=1
return t
有一个使用C++ 做的,时间复杂度可以达到,挺好的。
链接:
参考别人的代码:
改进如下:
class Solution:
"""
@param: n: An integer
@return: An integer, denote the number of trailing zeros in n!
"""
def trailingZeros(self, n):
# write your code here, try to do it without arithmetic operators.
number=0
while(n):
number+=int(n/5)
n=int(n/5)
return number