Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
public class Solution {
public int trailingZeroes(int n) {
int total = 0;
int base = 5;
while(n>=base) {
total += n/base;
if(base>Integer.MAX_VALUE/5) break;
base *= 5;
}
return total;
}
}
5倍数的个数,25倍数的个数,125倍数的个数,725倍数的个数。。。
=====
public class Solution {
public int trailingZeroes(int n) {
int res = 0;
int fives = 5;
int max = Integer.MAX_VALUE / 5;
while (true) {
int num = n / fives;
if (num == 0) break;
res += num;
if (max < fives) break;
fives *= 5;
}
return res;
}
}
=======
public class Solution {
public int trailingZeroes(int n) {
int res = 0;
if (n <= 0) {
return res;
}
while (n != 0) {
res += n / 5;
n /= 5;
}
return res;
}
}
没有评论:
发表评论