
n!中有几个0与[1,n]中出现多少个5的因数有关。例如7! = 1×2×3×4×5×6×7出现了1次5,故最后末尾会出现1个0。26!中出现了5,10,15,20,25其中5的个数为1+1+1+1+2=6,故最后末尾会出现6个0。
c++class Solution {
public:
    int cal(int k){
        if(k==0)
            return 0;
        else if(k%5==0){
            return cal(k/5)+1;
        }
        return 0;
    }
    int trailingZeroes(int n) {
        int count = 0;
        for (int i = 0;i<n+1;i+=5){
            count += cal(i);
        }
        return count;
    }
};

所以可知:
c++class Solution {
public:
    int trailingZeroes(int n) {
        int ans = 0;
        while (n) {
            n /= 5;
            ans += n;
        }
        return ans;
    }
};
复杂度:
本文作者:Geaming
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!