leetcode-172. 阶乘后的零

172. 阶乘后的零#

图床:blogimg/刷题记录/leetcode/172/

刷题代码汇总:https://www.cnblogs.com/geaming/p/16428234.html

题目#

image-20220828112313399

思路#

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。

解法#

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;
    }
};
  • 时间复杂度:O(n),其中n为数组nums的长度,需要遍历一遍数组
  • 空间复杂度:O(1),仅使用常量空间

补充#

image-20220828115103279

所以可知:

ans=n/5+n/52+n/53+

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

复杂度:

  • 时间复杂度:O(logn)
  • 空间复杂度:O(1)
posted @   Geaming  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩