Factorial Trailing Zeroes


Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

public class Solution {

    public int trailingZeroes(int n) {

        int result=1;


for(int i=1;i<=n;i++){


if ((i%5==0)||(i%10== 0)) result++;


}

return result;

    }

}


问题:给你一个整数n。返回n!的尾部的零的个数。

Note:算法的时间复杂度应该是对数级的

分析:

阶乘的结果的最后0的个数,5*一个偶数结尾为0. 10*任意数,结尾为0.

而5一定能遇到足够多的偶数来组成0,

所以就只需要统计1-n中,结尾为5和0的个数。

public class Solution {

    public int trailingZeroes(int n) {

        int result=1;


for(int i=1;i<=n;i++){


if ((i%5==0)||(i%10== 0)) result++;


}

return result;

    }

}


但是该解法的时间复杂度为O(N)。
给定一个N,那么其中1-N中是10的倍数的数的个数应该为N/10
5的倍数的数的个数应该为N/5.(但该数目包含了整除10的个数)
所以只跟5的整数倍的数个个数有关。
所以初步判断返回n/5就可以了。
比如11,则有5和10贡献2个0. 所以返回11/5 =2.
但是
注意:
对于25来说,其为5*5,提供2个5.
比如26:5,10,15,20,各贡献1个0,但是25贡献2个。
所以一共6个0 而不是5个。
最终算法:

result=n/5
如果n/5>5,

result +=(n/5)/5. 重复下去

public static int trailingZeroes(int n) {

int count = 0;

while (n / 5 >= 1) {

count += n / 5;

n /= 5;

}

return count;

}


你可能感兴趣的:(算法)