美文网首页北美程序员面试干货
LeetCode 172 [Factorial Trailing

LeetCode 172 [Factorial Trailing

作者: Jason_Yuan | 来源:发表于2016-08-01 14:42 被阅读2次

原题

设计一个算法,计算出n阶乘中尾部零的个数

样例
11! = 39916800,因此应该返回 2

解题思路

  • 数学问题,写成前几项找规律
5!, 包含1*5, 1个5 => 1个0
10!, 包含1*5,2*5, 2个5 => 2个0
15!, 包含1*5,2*5,3*5, 3个5 => 3个0
20!, 包含1*5,2*5,3*5,4*5, 4个5 => 4个0
25!, 包含1*5,2*5,3*5,4*5,5*5, 5个5 => 5个0
...
  • 所以本题就转化为,找1到n中包含几个5

完整代码

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

相关文章

网友评论

    本文标题:LeetCode 172 [Factorial Trailing

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