java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from right-1). If the binary expression does not contain any set bit, it returns 0.
public static long highestOneBit(long num) Parameters: num - the number passed Returns: long value by only considering highest 1 bit in the argument.
Input : 9 Output : 8 Explanation: Binary Representation = 1001 It considers highest bit(at 4th from right) and now reset rest of the bits i.e. 1000 so result = 1000 i.e. 8 or in simple terms, the last set bit position from right is at position 4, hence 2^3=8 Input : 45 Output : 32
The program below illustrates the java.lang.Long.highestOneBit() function:
highest one bit = 8 highest one bit = 32
Note: The negative number’s highest bit will always be the same in every case, hence irrespective of the number, the output will be same for every negative number.
Program 2: The program below demonstrates the use of function when a negative number is passed.
Binary = 1111111111111111111111111111111111111111111111111111111111110001 Highest one bit = -9223372036854775808
It returns an error message when a decimal a string value is passed as an argument.
Program 3: When a decimal value is passed in argument.
prog.java:13: error: incompatible types: possible lossy conversion from double to long System.out.println("highest one bit = " + Long.highestOneBit(12.34));
Program 3: When a string value is passed in argument.
prog.java:13: error: incompatible types: String cannot be converted to long System.out.println("highest one bit = " + Long.highestOneBit("12"));
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.