• lintcode :Trailing Zeros 尾部的零


    题目:

    设计一个算法,计算出n阶乘中尾部零的个数

    样例

    11! = 39916800,因此应该返回 2

    挑战

    O(logN)的时间复杂度

    解题:

    常用方法:

    也许你在编程之美中看到,通过求能够被2 整除和能够被5整除个数的最小值就是答案,或者直接求能够被5整除的个数就是答案<能够被5整除的数显然比较小>,但是在这里,java python都试了,结果都会出现运行超时或者越界的问题。

    维基百科中有如下计算方法:

    Java程序:

    class Solution {
        /*
         * param n: As desciption
         * return: An integer, denote the number of trailing zeros in n!
         */
        public long trailingZeros(long n) {
            // write your code here
            long count = 0;
            for(long i=5;n/i>=1;i*=5){
                count += n/i;
            }
            return count;
        }
    };
    View Code

    总耗时: 600 ms

    时间好快的

    Python程序:

    class Solution:
        # @param n a integer
        # @return ans a integer
        def trailingZeros(self, n):
            count = 0
            i = 5
            while n/i>=1:
                count +=n/i
                i = i * 5
            return count
    View Code

     总耗时: 98 ms

    在维基百科下面还有下面的方法:

    Java程序:

    class Solution {
        /*
         * param n: As desciption
         * return: An integer, denote the number of trailing zeros in n!
         */
        public long trailingZeros(long n) {
            // write your code here
            long q = n;
            long count = 0;
            while (q!=0){
                count +=q/5;
                q = q/5;
            }
            return count;
        }
    };
    View Code

    总耗时: 583 ms

    Python程序:

    class Solution:
        # @param n a integer
        # @return ans a integer
        def trailingZeros(self, n):
            count = 0
            p = n
            while p!=0:
                p = p/5
                count +=p
            return count
    View Code

    总耗时: 104 ms

  • 相关阅读:
    对线程的理解
    C#-设计模式-策略模式
    C#-设计模式-观察者模式
    C#-设计模式-模板方法
    C#-设计模式-适配器模式
    C#-设计模式-代理模式
    C#-设计模式-装饰模式
    C#-设计模式-简单工厂
    C#-设计模式-单例模式
    DotNet Core2.1 编写自己的中间件和后台服务
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4875114.html
Copyright © 2020-2023  润新知