美文网首页
172. Factorial Trailing Zeroes

172. Factorial Trailing Zeroes

作者: Leorio_c187 | 来源:发表于2017-06-15 09:47 被阅读0次

    题目

    Given an integer n, return the number of trailing zeroes in n!.

    Note: Your solution should be in logarithmic time complexity.

    思路

    • 后面的0是2*5产生的, 因为2的因子数量永远比5多,所以我们只要找有多少个5就好了
    • 像25这种数,里面有两个5的因子,怎么办? 举个例子,100!里面,有一个5的因子数的个数是100/5 = 20, 有两个5的因子个数是100/25 = 4。所以一共有24个。所以我们就可以用100一直除以5,把所得数相加。

    Python

    递归

    class Solution(object):
        def trailingZeroes(self, n):
            """
            :type n: int
            :rtype: int
            """
            #A very smart question, 2 is always ample, so we only need to care about the factor of 5
            return  0 if n == 0 else n/5 + self.trailingZeroes(n/5)
           
    

    循环

    class Solution(object):
        def trailingZeroes(self, n):
            """
            :type n: int
            :rtype: int
            """
            #A very smart question, 2 is always ample, so we only need to care about the factor of 5
            res = 0
            while n > 0:
                n /= 5
                res += n
            return res
           
    

    相关文章

      网友评论

          本文标题:172. Factorial Trailing Zeroes

          本文链接:https://www.haomeiwen.com/subject/wgjyqxtx.html