题目链接:factorial-trailing-zeroes
/**
*
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
*
*/
public class FactorialTrailingZeroes {
// 502 / 502 test cases passed.
// Status: Accepted
// Runtime: 195 ms
// Submitted: 0 minutes ago
//解题思路:只需计算5的倍数
//即 n/5^m 的个数之和
//5^1 5^2 5^3 5^4 ... 5^m <= n
static int trailingZeroes(int n) {
int fives = 0;
while(n / 5> 0) {
n = n / 5;
fives += n;
}
return fives;
}
// //超时
// static int trailingZeroes(int n) {
//
// int fives = 0;
//
// for (int i = 0; i <= n; i += 5) {
// int m = i;
// while(m % 5 == 0 && m != 0) {
// fives ++;
// m /= 5;
// }
// }
// return fives;
// }
public static void main(String[] args) {
System.out.println(trailingZeroes(1808548329));
}
}