Home » Java Integer numberOfLeadingZeros() method with Examples

Java Integer numberOfLeadingZeros() method with Examples

by Online Tutorials Library

Java Integer numberOfLeadingZeros() Method

The numberOfLeadingZeros() method is a method of Integer class under java.lang package. This method returns the total number of zero bits preceding the highest-order (“leftmost”) one-bit in the two’s complement binary representation of the specified integer value i.e. it converts int value to Binary then considers the highest one bit and returns total number of zero bits preceding it. In other words, if the specified integer value has no one-bits or is equal to zero in its two’s complement representation then it will return 32.

Note: This method is closely related to the logarithm base 2. For all positive int values x:

Exaplanation:

Syntax:

Following is the declaration of numberOfLeadingZeros() method:

Parameter:

DataType Parameter Description Required/Optional
int i It accepts integer value which returns highest order bit on its 2’s complement. Required

Returns:

The 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 integer value, or 32 if the value is equal to zero.

Exceptions:

NA

Compatibility Version:

Java 1.5 and above

Example 1

Test it Now

Output:

Leading Zero's: 28  

Example 2

Test it Now

Output:

Binary equivalent: 110111  Number of Leading Zeros: 26  

Example 3

Output:

Enter the desired Integer value: 75  Binary equivalent: 1001011  Number of Leading Zeros: 25  

Example 4

Test it Now

Output:

Input Number = -15  Number of Leading Zeros = 0  

Example 5

Test it Now

Output:

Leading Zero's: 32  

You may also like