zoukankan      html  css  js  c++  java
  • [LeetCode]66. Factorial Trailing Zeros阶乘的尾零个数

    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.

    Subscribe to see which companies asked this question

     
    解法1:如果N! == K×10M, ( 0 != k%10 ),那么M就是要求的。我们把N!进行质因数分解,则有 N! == 2* 3Y * 5Z……,而10是怎么来的呢,分解之后不就只能由2×5来。也就是说,只要求分解后的min(x, z),又显然,分解之后2的个数显然要比5的个数多。所以,M == Z。根据分析,要计算 Z,最直接的方法,就是计算i(i =1, 2, …, N)的因式分解中5 的指数,然后求和。
    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0, j;
            for (int i = 5; i <= n; i += 5) {
                int j = i;
                while (j % 5 == 0) {
                    ++cnt;
                    j /= 5;
                }
            }
            return cnt;
        }
    };

    这种解法会在N超大时超时Time Limit Exceeded。题目的Note要求我们写出对数时间复杂度的解法。

    解法2:在解法1的基础上考虑到能贡献5的数全是5的倍数,而5的指数(5,25,125,...)能贡献5的个数恰好是幂的值(1,2,3,...),非5的指数(10,15,20,30,,...)则只能贡献一个5。而使用N除以5可以得到在[1,N]中有多少个5的倍数,除以25可以得到有多少个25的倍数……这样所有的结果加起来恰好可以算出[1,N]中一共有多少个5。注意25=5*5即可以贡献两个5,而在前面除以5的时候已经计算过一次了,所以加1次就可以了,同理125=5*5*5,在2和25的时候已经考虑到两个5了,所以后面也是再加一个就行了,后面所有5的指数都如此。

    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0;
            long long k = 5;
            while(k <= n) {
                cnt += n / k;
                k *= 5;
            }
            return cnt;
        }
    };

    注意k必须定义为long long类型以防止在n极大时k会溢出。一个避免这个陷阱的写法如下:

    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0;
            while(n > 0) {
                cnt += n / 5;
                n /= 5;
            }
            return cnt;
        }
    };
  • 相关阅读:
    数据库连接,报错--mysql版本不匹配
    SpringMVC项目如何添加事物呢
    将存放数字的list,顺序排列,然后,判断,数字是否是连续的
    list从小到大,排序----这么简单
    SpringMVC控制层,setViewName--不能跳转到指定视图
    SpringMVC中jsp和controller互传参的问题
    jsp到controller乱码
    PDF 补丁丁 0.4.1 版:新增嵌入中文字库、替换文档字库的功能
    PDF 补丁丁 0.4.1 版将增加嵌入中文字库的功能
    Django视图层
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4949015.html
Copyright © 2011-2022 走看看