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


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