The ** numberOfLeadingZeros() method** of the

`Integer`

class is a static method used to get the total number of zero bits preceding the Let’s understand this method with the help of examples.

- 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`

.

- 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`

.

```
public static int numberOfLeadingZeros(int i)
```

`int i`

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

- 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`

.

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);}}

TRENDING TOPICS