Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count in Java the trailing zeros from an Integer? (Ex: 234000 => 3 zeros)

Tags:

java

integer

The title is pretty much self explanatory. :)

1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5
like image 352
chrisapotek Avatar asked Sep 10 '14 19:09

chrisapotek


People also ask

How do you count the number of trailing zeros in Java?

Trailing 0s in n! = Count of 5s in prime factors of n! = floor(n/5) + floor(n/25) + floor(n/125) + ....

How do you count trailing zeros?

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).


2 Answers

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++;
}
like image 194
Luiggi Mendoza Avatar answered Oct 05 '22 23:10

Luiggi Mendoza


Integer class has an inbuilt function to count the trailing zeros. javadocs

int trailingZeroes = Integer.numberOfTrailingZeros(int i);
like image 25
Arjun S Avatar answered Oct 05 '22 23:10

Arjun S