English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java's Integer.numberOfLeadingZeros() method

The Java Integer.numberOfLeadingZeros() method returns the number of leading zeros before the highest bit ("leftmost") in the binary representation of the specified int value.

We take the following decimal as an example.

int dec = 294;

Calculate the binary using Integer.toBinaryString() as shown below-

Integer.toBinaryString(dec);

Now let's take a look at the implementation of the Integer.numberOfLeadingZeros() method.

Example

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 Result

Decimal = 294
Binary = 100100110
Count of one bits = 4
Lowest one bit: 2
Number of leading zeros: 23