The numberOfTrailingZeros()
method of Integer class, returns number of zero-bits after the last one-bit in the binary representation of the given int number.
Returns 32 if there are no one-bit in the binary representation of the given int number (which means number is zero).
Syntax of numberOfTrailingZeros() method
public static int numberOfTrailingZeros(int i)
numberOfTrailingZeros() Parameters
i
– An int value whose number of trailing zeroes to be computed.
numberOfTrailingZeros() Return Value
- Returns number of zero bits following the lowest-order (rightmost) one bit.
Supported versions: Java 1.5 and onwards.
Example 1
Here, we have a number 20, whose number of trailing zeroes needs to be computed. There are only two zeroes after the last one-bit in the number so this method returns 2 as result.
class JavaExample { public static void main(String args[]) { //two's complement binary representation of 20: // 0000 0000 0000 0000 0000 0000 0001 0100 int i = 20; System.out.print("Number of trailing zero bits: "); System.out.print(Integer.numberOfTrailingZeros(i)); } }
Output:
Example 2
Unlike numberOfLeadingZeros() method, where sign of the number changes the result. In this method, Number of trailing zeroes are same for positive and negative number, if the absolute values of the given numbers are same.
class JavaExample { public static void main(String args[]) { int i = 20; int i2 = -20; System.out.print("Trailing zero bits in +20: "); System.out.println(Integer.numberOfTrailingZeros(i)); System.out.print("Trailing zero bits in -20: "); System.out.println(Integer.numberOfTrailingZeros(i2)); } }
Output: