lintcode 求n!中末尾0 的个数

我们只需要考虑哪些数相乘可以得到10即可,因为2*5 = 10,因此我们只需要找到2和5的个数的较小的一个值,因为能被2整除的数多于能被5整除的数,因此题目转换成包含因子5的个数。
代码如下:

class Solution {
 public:
    // param n : description of n
    // return: description of return 
    long long trailingZeros(long long n) {
        long long num = 0;
        for (int i = 5;i <= n;i += 5) {
            int j = i;
            while (j % 5 == 0) {
                num++;
                j /= 5;
            }
        }
        return num;
    }
};

可是提交的时候显示超过了时间限制,于是不得不考虑另一种方法。
设X = (n/5) + (n/(5*5)) ......
也就是说不大于n的数中,能被5整除的数贡献一个5,能被25整除的数再贡献一个5......
代码如下:

class Solution {
 public:
    // param n : description of n
    // return: description of return 
    long long trailingZeros(long long n) {
        long long num = 0;
        while (n) {
            num += n/5;
            n /= 5;
        }
        return num;
    }
};
  

通过。

你可能感兴趣的:(lintcode 求n!中末尾0 的个数)