Integer.numberOfLeadingZeros() method in Java

Java 8Object Oriented ProgrammingProgramming

This Integer.numberOfLeadingZeros() method in Java 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.

We have the following decimal as an example.

int dec = 294;

Calculated binary using Integer.toBinaryString() as shown below −

Integer.toBinaryString(dec);

Now let us see the implementation of Integer.numberOfLeadingZeros() method.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      int dec = 294;
      System.out.println("Decimal = " + dec);
      System.out.println("Binary = " + Integer.toBinaryString(dec));
      System.out.println("Count of one bits = " + Integer.bitCount(dec));
      System.out.println("Lowest one bit: " + Integer.lowestOneBit(dec));
      System.out.println("Number of leading zeros: " + Integer.numberOfLeadingZeros(dec));
   }
}

Output

Decimal = 294
Binary = 100100110
Count of one bits = 4
Lowest one bit: 2
Number of leading zeros: 23
raja
Published on 13-Nov-2018 05:12:17
Advertisements