首页 > 其他分享 >leetcode-172. 阶乘后的零

leetcode-172. 阶乘后的零

时间:2022-08-28 12:02:14浏览次数:76  
标签:return int 复杂度 172 ans 阶乘 leetcode

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)\)

标签:return,int,复杂度,172,ans,阶乘,leetcode
From: https://www.cnblogs.com/geaming/p/16632514.html

相关文章

  • CF1721D(Edu134Div2-D)
    原题链接一个显然的结论是,从高位道低位考虑答案在这一位是否可以是1,那么如果一个高位可以为1,那么一定不会为了其他低位而把它变成0。另一个结论是:如果一个高位不能变成1,那......
  • LeetCode 1166. Design File System
    原题链接在这里:https://leetcode.com/problems/design-file-system/题目:Youareaskedtodesignafilesystem thatallowsyoutocreatenewpathsandassociatet......
  • LeetCode/阶乘后的零
    1.返回尾零数量可以转换为求质因子为2和5数量的较小值,实际上就是求质因子为5的数量classSolution{public:inttrailingZeroes(intn){intans=0;......
  • 【重要】LeetCode 662. 二叉树最大宽度
    题目链接注意事项根据满二叉树的节点编号规则:若根节点编号为u,则其左子节点编号为u<<1,其右节点编号为u<<1|1。一个朴素的想法是:我们在DFS过程中使用两个哈希表......
  • leetcode 647. Palindromic Substrings回文子串(中等)
    一、题目大意给你一个字符串s,请你统计并返回这个字符串中回文子串的数目。回文字符串是正着读和倒过来读一样的字符串。子字符串是字符串中的由连续字符组成的一......
  • leetcode139:单词拆分
    packagecom.mxnet;importjava.util.HashSet;importjava.util.List;publicclassSolution139{publicstaticvoidmain(String[]args){}/**......
  • LeetCode刷题23-在排序数组中查找元素的第一个和最后一个位置
    importjava.util.Arrays;/***功能描述**@authorASUS*@version1.0*@Date2022/8/27*/publicclassMain06{publicstaticvoidmain(String[]......
  • leetcode169:多数元素
    packagecom.mxnet;importjava.util.HashMap;importjava.util.Set;publicclassSolution169{publicstaticvoidmain(String[]args){}/**......
  • [Oracle] LeetCode 348 Design Tic-Tac-Toe
    Assumethefollowingrulesareforthetic-tac-toegameonannxnboardbetweentwoplayers:Amoveisguaranteedtobevalidandisplacedonanemptybloc......
  • 动态规划——leetcode5、最长回文子串
    1、题目描述:2、解题方法:动态规划动态规划解题步骤:1、确定状态最后一步:如果s[i,...,j]是回文子串,那么需要满足两个条件①s[i......