Java.lang Package Classes

Java Integer - numberOfLeadingZeros() Method



The java.lang.Integer.numberOfLeadingZeros() method returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value. The method returns 32 if the specified value has no one-bits in its two's complement representation, in other words if it is equal to zero.

For all positive int values x:

  • floor(log2(x)) = 31 - numberOfLeadingZeros(x)
  • ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)

Syntax

public static int numberOfLeadingZeros(int i)

Parameters

i Specify the value whose number of leading zeros is to be computed.

Return Value

Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value, or 32 if the value is equal to zero.

Exception

NA.

Example:

In the example below, the java.lang.Integer.numberOfLeadingZeros() method returns the number of zero bits preceding the leftmost one-bit in the two's complement binary representation of the given int value.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating an int value
    int x = 75; 

    //printing value of x, its binary 
    //representation and numberOfLeadingZeros
    System.out.println("The values of x is: " + x);
    System.out.print("The binary representation of x is: ");
    System.out.println(Integer.toBinaryString(x));
    System.out.print("The numberOfLeadingZeros is: ");
    System.out.println(Integer.numberOfLeadingZeros(x));
  }
}

The output of the above code will be:

The values of x is: 75
The binary representation of x is: 1001011
The numberOfLeadingZeros is: 25

❮ Java.lang - Integer