算法 Trailing Zeros

計算出n階乘中尾部零的個數

樣例  1:
    輸入: 11
    輸出: 2
    
    樣例解釋: 
    11! = 39916800, 結尾的0有2個。

樣例 2:
    輸入:  5
    輸出: 1
    
    樣例解釋: 
    5! = 120, 結尾的0有1個。

分析:尾數的個數是根據素因子分解 則存在 2*5產生尾數0 所以可以確定出5的個數即爲0的個數

class CalculateZeros{
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        long sum = 0;
        while (n != 0) {
            sum += n / 5;
            n /= 5;
        }
        return sum;
    }
};

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章