The Integer.numberOfLeadingZeros(int value) method returns the number of zero bits before the first (leftmost) 1-bit in the binary representation of the given integer. If the value is 0 (i.e., no 1-bits), it returns 32.
Syntax :
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.
Program 1: Below programs illustrate the java.lang.Integer.numberOfLeadingZeros() method. with positive number.
public class LeadingZeros {
public static void main(String[] args) {
int a = 19;
System.out.println("Integral Number = " + a);
// Returns the number of zero bits preceding the highest-order one-bit
System.out.print("Number of Leading Zeros = ");
System.out.println(Integer.numberOfLeadingZeros(a));
}
}
Output
Integral Number = 19 Number of Leading Zeros = 27
Explanation:
- Consider any integer arg, like int arg = 19;
- Binary Representation(32-bit) of 19 = 00000000 00000000 00000000 00010011
- First (leftmost) 1 bit is at position 27 (index starts from 0).
- number of leading zeros = 32 - 5 = 27
Program 2: For a negative number.
public class LeadingZeros {
public static void main(String[] args) {
int a = -15;
System.out.println("Number = " + a);
// Returns the number of zero bits preceding the highest-order one-bit
System.out.print("Number of Leading Zeros = ");
System.out.println(Integer.numberOfLeadingZeros(a));
}
}
Output
Number = -15 Number of Leading Zeros = 0
Program 3: For a decimal value.
public class LeadingZeros {
public static void main(String[] args) {
// Cast double to int explicitly
System.out.print("Number of Leading Zeros = ");
System.out.println(Integer.numberOfLeadingZeros((int) 16.32));
}
}
Output
Number of Leading Zeros = 27
Note:It returns an error message when a decimal value is passed as an argument.
Program 4: For a string value is passed in argument.
public class LeadingZeros {
public static void main(String[] args) {
// Convert String to int
int number = Integer.parseInt("18");
// Returns the number of zero bits preceding the highest-order one-bit
System.out.print("Number of Leading Zeros = ");
System.out.println(Integer.numberOfLeadingZeros(number));
}
}
Output
Number of Leading Zeros = 27
Note:It returns an error message when a string is passed as an argument.