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

[Lintcode]2. Trailing Zeros

时间:2019-02-10 09:38:59      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:com   note   rom   do it   which   ref   难度   sel   .com   

2. Trailing Zeros

  • 本题难度: Easy
  • Topic: Math&Bit Manipulation

    Description

    Write an algorithm which computes the number of trailing zeros in n factorial.

Example
Example 1:
Input: 11
Output: 2

Explanation: 
11! = 39916800, so the output should be 2

Example 2:
Input: 5
Output: 1

Explanation: 
5! = 120, so the output should be 1.

Challenge
O(log N) time

我的代码

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.
        count = 0
        f = 5
        while(f<n):
            count += n//f
            f *= 5
        return count

思路

每一个末尾处为0都是有5和2相乘得出来的,2出现的频率远远高于5,所以不需要考虑2出现的情况。只需要考虑分解质因数出现了多少个5即可

[Lintcode]2. Trailing Zeros

标签:com   note   rom   do it   which   ref   难度   sel   .com   

原文地址:https://www.cnblogs.com/siriusli/p/10358619.html

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