What is Integer.numberOfTrailingZeros() in Java?
The numberOfTrailingZeros() method of the Integer class is a static method that we can use to get the total number of zero bits. These zero bits follow the integer value.
This method returns 32 if there are no one-bits in the binary representation of the integer value.
Syntax
public static int numberOfTrailingZeros(int i)
Parameters
int i: The integer value whose number of trailing zeros is to be computed.
Return value
numberOfTrailingZeros() returns the number of trailing zeros in the 32-bit representation of the integer.
Examples
Let’s understand this method with the help of a few examples.
Example 1
intvalue:123- Binary representation of
123: 1111011
The lowest one-bit of 123 in its binary representation is the rightmost one-bit.
The number of trailing zeros for 123 is 0.
Example 2
intvalue:12- Binary representation of
12: 1100
The lowest one-bit of 12 in its binary representation is at position 2.
The number of trailing zeros for 12 is 2.
Code
public class Main{private static void numberOfTrailingZeros(int number){System.out.println("Binary Representation of " + number + " - " + Integer.toBinaryString(number));System.out.println("Number of Trailing Zeros of " + number + " - "+ Integer.numberOfTrailingZeros(number));}public static void main(String[] args){numberOfTrailingZeros(123);System.out.println("----------");numberOfTrailingZeros(0);System.out.println("----------");numberOfTrailingZeros(12);}}