您的位置:首页 > 大数据 > 人工智能

LeetCode Factorial Trailing Zeroes

2016-05-29 21:39 495 查看

LeetCode解题之Factorial Trailing Zeroes

原题

求n的阶乘末尾有几个零。

注意点:

将时间复杂度控制为log(n)

例子:

输入: n = 5

输出: 1

解题思路

通过因数分解知道,10是由2和5相乘得到的,而在n的阶乘中,因子2的数目总是比5多的,所以最终末尾有几个零取决于其中有几个5。1到n中能够整除5的数中有一个5,能整除25的数有2个5(且其中一个在整除5中已经计算过)…所以只要将n不断除以5后的结果相加,就可以得到因子中所有5的数目,也就得到了最终末尾零的数目。

AC源码

class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
n //= 5
count += n
return count

if __name__ == "__main__":
assert Solution().trailingZeroes(25) == 6


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息