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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

分析

题目描述:给定一个整数末尾0的个数。

开始看到的时候并没有什么思路,只知道

那么末尾而导致的结果 , 又搜索了网上一些资料:

对n!做质因数分解

显然

证明:

对于阶乘而言,也就是整除的个数
那么很显然
(左边是逢4增1,右边是逢25增1)
……
增1)
随着幂次的概率。
因此左边的加和一定大于右边的加和,也就是的次幂

此时,便很明了了,结果可以表示为:

AC代码

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

相关文章: