非常有意思的一道题目,读研的时候当家教,在一个小学奥数辅导班上见到过这个题,先介绍阶乘的概念,然后问结果中有多少个0,很多年过去了,再看这道题感觉很有缘分。

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

结果中有0,实际是判断5的个数,如果n > 25,实际上还要判断包含多少个25,因为25中包含两个5,原来加过一个,还需要再加一次,如果n >125,那么还要再加第三次,依次类推。

2021.04.04笔记

时隔小半年再次看这道题,直接AC代码:

class Solution {
public:
    int trailingZeroes(int n) {
        int cnt = 0;
        for(int i = 1;i <= n;i++)
        {
            int num = i;
            while(num%5==0)
            {
                cnt++;
                num /= 5;
            }
        }
        
        return cnt;
    }
};

运行效率较差:

Runtime: 4 ms, faster than 16.11% of C++ online submissions for Factorial Trailing Zeroes.
Memory Usage: 6 MB, less than 22.15% of C++ online submissions for Factorial Trailing Zeroes.

看了下讨论区,发现存在更简单的解法,其实没有必要从1开始遍历,只用遍历5的倍数即可。

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

运行效率:

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Factorial Trailing Zeroes.
Memory Usage: 6 MB, less than 22.15% of C++ online submissions for Factorial Trailing Zeroes.