首页 > 其他 > 详细

lintcode 容易题:Trailing Zeros 尾部的零

时间:2015-10-13 18:36:39      阅读:749      评论:0      收藏:0      [点我收藏+]

题目:

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

样例

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

挑战

O(logN)的时间复杂度

解题:

通过直接求 1 到n 中5的个数 运行会超时。。。

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

技术分享

技术分享

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

 

lintcode 容易题:Trailing Zeros 尾部的零

原文:http://www.cnblogs.com/theskulls/p/4875114.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!