2. 尾部的零【简单】

设计一个算法,计算出n阶乘中尾部零的个数。

思路:0的个数取决于5因子的个数,5的一次方对答案贡献一个0,5的平方贡献两个0,5的三次方贡献3个0......以此类推。

代码:

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 long cnt=0;
            long long b=5;
            long long tmp;
            while(tmp)
            {
                tmp=n/b;
                cnt+=tmp;
                b*=5;
            }
            return cnt;
        }
};

 

posted @ 2018-01-24 17:54  陈阿毛  阅读(105)  评论(0)    收藏  举报