尾部的零

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

样例

11! = 39916800,因此应该返回 2

挑战

O(logN)的时间复杂度


**************************

各种超时 …… 编程之美上的这个思路也超时

class Solution {
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        // write your code here
        int num = 0, i;
		for(i=5; i<=n; i*=5)
		{
			num += n/i;
		}
		return num;
    }
};
过了的代码

最后尾数为0 都是偶数和5相乘得到的所有把 数字都拆分 看有多少个5

class Solution {
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        // write your code here
        long num = 0, i;
		while(n >= 5){
		    num += n /5;
		    n = n / 5;
		}
		return num;
    }
};


你可能感兴趣的:(算法,面试,设计,lintcode,数字与二进制)