Integer.numberOfLeadingZeros() Method in Java With Example
The java.lang.Integer.numberOfLeadingZeros() is the method which returns the total number of zero(0) bits preceding the highest-order (ie.leftmost or most significant “1” bit)one-bit in the two’s complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. If the specified integer value has no one-bits in its two’s complement representation, in other words if it is equal to zero then it will returns 32.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public static int numberOfLeadingZeros(int arg)
Parameter : This method accepts a single parameter arg which is the integer value.
Return Value : This method returns the number of zero bits preceding the highest-order set-bit in the two’s complement binary representation of the specified int value, or 32 if the value is equal to zero.
- Consider any integer arg = 19
- Binary Representation = 0001 0011
- Highest bit(at 5) i.e.0001 0000
- so result = 16-5 i.e. 11
Below programs illustrate the java.lang.Integer.numberOfLeadingZeros() method.
Program 1: For a positive number.
Integral Number = 155 Number of Leading Zeros = 24 Integral Number = 10 Number of Leading Zeros = 28
Program 2: For a negative number.
Number = -15 Number of Leading Zeros = 0
Program 3: For a decimal value.
Note:It returns an error message when a decimal value is passed as an argument.
prog.java:11: error: incompatible types: possible lossy conversion from double to int System.out.println(Integer.numberOfLeadingZeros(16.32)); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error
Program 4: For a string value is passed in argument.
Note:It returns an error message when a string is passed as an argument.
prog.java:11: error: incompatible types: String cannot be converted to int System.out.println(Integer.numberOfLeadingZeros("18")); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error