[LeetCode] Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

计算n!结果的末尾有几个零。

题目要求复杂度为对数,所以不能使用暴力算法:即先计算n!,然就依次除以10计算0个个数。

末尾的零是由2 * 5得到的,所以需要计算n中2和5的个数即可。又因为2的个数远多于5的个数,只要计算5的个数即可。

class Solution {
public:
    int trailingZeroes(int n) {
        int res = 0;
        while (n) {
            n /= 5;
            res += n;
        }
        return res;
    }
};
// 3 ms
原文地址:https://www.cnblogs.com/immjc/p/7619872.html