简体   繁体   中英

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

The title is pretty much self explanatory. :)

1232 => 0
1231030 => 1
2000 => 3
34444400000 => 5

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++;
}

Three lines:

int zeroes = 0
while(num%10 == 0 && num != 0) {
  zeroes++;
  num /= 10;
}

This uses the modulus operator. As long as we can divide by ten without remainder, increment the counter.

Here is another solution using Java 8 Streams:

int trailingZeros = String.valueOf(number).chars()
        .reduce(0, (count, ch) -> (ch == '0') ? count + 1 : 0);

This transforms the number to an IntStream. This stream is then reduced using a lambda which resets a counter each time a non-zero char comes up.

You could always just use a regular expression:

Pattern pattern = Pattern.compile("(0+)$");
Matcher matcher = pattern.matcher(String.valueOf(123140000));
Integer trailingZeroes = 0;
if (matcher.find()) {
    trailingZeroes = matcher.group(1).length();
} 
System.out.println(trailingZeroes);

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

int trailingZeroes = Integer.numberOfTrailingZeros(int i);

Not tried this code but this should work.

int counterForZeros=0;
for(long i=10;true;)
{
    if(num%i==0)
    {
        counterForZeros++;
        i*=10;
    }
    else 
    {
        break;
    }
}
System.out.println("Number of zeros in "+num+" is "+counterForZeros);

you can turn the int to a String and iterate in reverse, counting the zeros until you find a char that is not zero:

int countZeros(int x){
    String a = Integer.toString(x);
    int numOfZeros = 0;
    for(int i = a.length() - 1; i >= 0; i--)
        if (a.charAt(i) != '0') break;
        else numOfZeros ++;

    return numOfZeros;          
}

Testing with :
System.out.println(countZeros(25000)); will print 3
System.out.println(countZeros(25)); will print 0

Hope this helps.

好吧,如果这是一场比赛,看谁能用最少的台词做到这一点:

trailingZeroes = String.valueOf(num).length() - String.valueOf(num).replaceAll("0*$","").length();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM