Write an algorithm which computes the number of trailing zeros in n factorial.
这道题的思路比较诡异,结尾要有0的话,必须要有质因数2和质因数5,而任何一个数的阶乘,质因数2的个数会比质因数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 if(n <= 0) return 0; long result = 0; for(long i = 5; n / i > 0; i *= 5){ result += n / i; } return result; } };
原文:http://www.cnblogs.com/goblinengineer/p/5251330.html