LeetCode 172. Factorial Trailing Zeroes 阶乘后的零

题目链接:点击这里
在这里插入图片描述
n ! n! 后缀零的个数,也就是 10 10 的个数,也就 ( 2 5 ) (2*5) 的个数,由于 5 5 2 2 的次数要少,因此统计 5 5 的个数即可。
n u m = a 1 0 k = a 2 k 5 k num = a*10^k = a* 2^k*5^k

class Solution {
public:
    int trailingZeroes(int n) {
        int cnt = 0;

        //for(int i = 1; i <= n; i++) {
        for(int i = 5; i <= n; i += 5) {
            int x = i;
            while(x%5==0) {
                cnt++;
                x /= 5;
            }
        }
        return cnt;
    }
};

在这里插入图片描述优化:

class Solution {
public:
    int trailingZeroes(int n) {
        int cnt = 0;
        while(n>0) {
            cnt += n/5;
            n /= 5;
        }
        return cnt;
    }
};
发布了690 篇原创文章 · 获赞 103 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104060159