Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
题目大意是说找出n!算出的数末尾有多少个零。
找末尾零就相当于找从1到n中有多少个2和5,如果用for(i = 1; i <= n; i++)遍历,统计可被2除和可被5除的个数,然后返回两个个数中较少的一个,可以达到计算结果但是会超时。
2和5的个数,一定是2比5多,所以只需要计算5的个数就可以了,遍历依然超时。这时可以这么想,用一个循环控制n / 5来计算从1到n中5的个数。比如10,10 / 5 = 2,则从1到10中总共因式分解可得两个5。但注意如25这种,必须是用循环除尽才可得,因为25本身就包含两个5。
Source
public int trailingZeroes(int n) {
if(n <= 1) return 0;
int count = 0;
while(n / 5 != 0){
n = n / 5;
count = count + n; //***
}
return count;
}
Test
public static void main(String[] args){
System.out.println(new Solution().trailingZeroes(125));
}