leetcode-172. 阶乘后的零

2022/8/28 23:27:54

本文主要是介绍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/5^2+n/5^3+\cdots\)

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

复杂度:

  • 时间复杂度:\(O(log\,n)\)
  • 空间复杂度:\(O(1)\)


这篇关于leetcode-172. 阶乘后的零的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程