letecode [172] - Factorial Trailing Zeroes

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

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

题目大意

   给定一个整数,求它的阶乘末尾0的个数。

理  解:

  n的阶乘可表示为x*(10^k) = x*(2^k * 5^k)。显然,2的数量比5的数量多,所以,k的个数由5的个数决定。

  比较直观的解法,求每个数中因子5的个数,但这样的做法会超出时间限制。

  其实,可以这样表示。N = n! = [N/5] + [N/(5*5)] + [N/(5*5*5)] + ...

  [N/5]表示小于N的数中贡献一个5的数量,[N/(5*5)]表示小于N的数中贡献两个5的数量...

  代码中N = N/5 是为了求得第m次贡献5的值。这个方法一直想不通,原来是方向想错了,今天看到网上的这个解释才明白。

代 码 C++:

class Solution {
public:
    int trailingZeroes(int n) {
        int count = 0;
        while(n>=5){
            count += n/5;
            n /= 5;
        }
        return count;
    }
};

运行结果:

  执行用时 :0 ms, 在所有C++提交中击败了100.00%的用户

  内存消耗 :8.3 MB, 在所有C++提交中击败了74.14%的用户
posted @ 2019-06-14 10:57  lpomeloz  阅读(95)  评论(0编辑  收藏  举报