The title is pretty much self explanatory. :)
1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5
Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) + floor(n/25) + floor(n/125) + ....
A simple method is to first calculate factorial of n, then count trailing 0s in the result (We can count trailing 0s by repeatedly dividing the factorial by 10 till the remainder is 0).
If it fits into an int
/long
, just check if the number modulo 10 is 0 and keep a counter:
long x = ...
if (x == 0) {
return 0;
}
int counter = 0;
while (x % 10 == 0) {
counter++;
x /= 10;
}
If it's too big to fit in long
, store it in a String
and count zeroes from the last char:
String s = ...
int counter = 0;
while(counter < s.length() && s.charAt(s.length() - 1 - counter) == '0') {
counter++;
}
Integer class has an inbuilt function to count the trailing zeros. javadocs
int trailingZeroes = Integer.numberOfTrailingZeros(int i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With