lintcode-easy-Trailing Zeros

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;
    }
};

 

posted @ 2016-03-07 17:43  哥布林工程师  阅读(102)  评论(0编辑  收藏  举报