Lintcode題目計算n階乘中尾部0的個數



用10!這個數字做思考,發現每五個數得到一個0,總結規律

z=n/5+n/(5*5)+n/(5*5*5)+…+(直到n小於n的a次冪)    //來源公式之美

代碼如下:

class Solution {
public:
    /*
     * @param n: A long integer
     * @return: An integer, denote the number of trailing zeros in n!
     */
    long long trailingZeros(long long n) {
        // write your code here, try to do it without arithmetic operators.
        long num = 0;
        while(n > 0) {
            num += n / 5;
            n /= 5;
        }
        return num;
    }
};


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