java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it returns 64.
public static long numberOfLeadingZeros(long num) Parameters: num - the number passed Returns: the number of leading zeros before the highest-order set bit
Input : 8 Output : 60 Explanation: Binary representation of 8 is 1000 No of leading zeros to the left of the highest-order set bit is 60. Input : 25 Output : 59
The program below illustrates the java.lang.Long.numberOfLeadingZeros() function:
Number of leading zeros = 60 Number of leading zeros = 59
Note: In case of a negative number, every number will have 0 leading zeros.
Program 2: The program below demonstrates the use of function when a negative number is passed.
Number of leading zeros = 0 Number of leading zeros = 0
Program 3: It returns an error message when a decimal a string value is passed as an argument.
prog.java:16: error: incompatible types: possible lossy conversion from double to long + Long.numberOfLeadingZeros(10.45));
Program 4: When a string value is passed in argument.
prog.java:16: error: incompatible types: String cannot be converted to long + Long.numberOfLeadingZeros("10"));
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.