首页 > 其他 > 详细

lintcode-easy-Trailing Zeros

时间:2016-03-07 18:36:02      阅读:182      评论:0      收藏:0      [点我收藏+]

Write an algorithm which computes the number of trailing zeros in n factorial.

11! = 39916800, so the out should be 2

 

这道题的思路比较诡异,结尾要有0的话,必须要有质因数2和质因数5,而任何一个数的阶乘,质因数2的个数会比质因数5多很多,所以只需要算出有多少个质因数5就可以了

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
        if(n <= 0)  
            return 0;
        
        long result = 0;
        
        for(long i = 5; n / i > 0; i *= 5){
            result += n / i;
        }
        
        return result;
    }
};

 

lintcode-easy-Trailing Zeros

原文:http://www.cnblogs.com/goblinengineer/p/5251330.html

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