Lintcode 2: 尾部的零

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


解析:仔细分析这个题,n!=1*2*,,,,,*n要产生0,就要有5,但是坑就在有25,125,,,,,这种多个5组成,考虑这个就ok啦。燃鹅人老了,忘了把计数器定义成long long类型。


c++版本:

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 count = 0;
	while (n>0)
	{
	    
	    n=n/5;
		count =count+ n;
	}
	return count;
}

};


Python版:

class Solution:
    """
    @param: n: An integer
    @return: An integer, denote the number of trailing zeros in n!
    """
    def trailingZeros(self, n):
        # write your code here, try to do it without arithmetic operators.
        count=0
        while n>0:
            n=n/5
            count+=n
        return count



你可能感兴趣的:(lintcode)