码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Factorial Trailing Zeroes

时间:2016-05-30 15:00:44      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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) 来获得相关源码。

LeetCode Factorial Trailing Zeroes

标签:

原文地址:http://blog.csdn.net/u013291394/article/details/51534156

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!