What is Integer.numberOfLeadingZeros() in Java?

The numberOfLeadingZeros() method of the Integer class is a static method used to get the total number of zero bits preceding the highest-orderleftmost one-bit in the two’s complement binary form of the provided integer value.


Examples

Let’s understand this method with the help of examples.

Example 1

  • int value: 123
  • Binary Representation of 123: 1111011

The highest one bit of the 123 in its binary representation is at position 7, i.e., the leftmost one-bit.

Now, the number of leading zeros can be calculated using the formula below.

number-of-leading-zeros = 32
This is the index of the leftmost one-bit.

The number of leading zeros for 123 is 32 - 7 = 25.

Example 2

  • int value: 12
  • Binary Representation of 12: 1100

The highest one bit of the 12 in its binary representation is at position 4, i.e., the leftmost one-bit.

Now, the number of leading zeros can be calculated using the formula below.

number-of-leading-zeros = 32
This is the index of the leftmost one-bit.

The number of leading zeros for 12 is 32 - 4 = 28.


Syntax

public static int numberOfLeadingZeros(int i)

Parameters

  • int i: The integer value whose number of leading zeros is to be computed.

Return value

  • The function returns the number of leading zeros in the 32-bit representation of the integer.

If there are no one-bits in the binary representation of the integer value, then this method returns 32.

Code

public class Main{
private static void numberOfLeadingZeros(int number){
System.out.println("Binary Representation of " + number + " - " + Integer.toBinaryString(number));
System.out.println("Number of Leading Zeros of " + number + " - "+ Integer.numberOfLeadingZeros(number));
}
public static void main(String[] args){
numberOfLeadingZeros(123);
System.out.println("----------");
numberOfLeadingZeros(0);
System.out.println("----------");
numberOfLeadingZeros(12);
}
}

Free Resources