java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position 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^(first set bit position from right-1). If the binary expression does not contain any set bit, it returns 0.
public static long lowestOneBit(long num) Parameters: num - the number passed Returns: long value by only considering lowest 1 bit in the argument.
Input : 36 Output : 4 Explanation: Binary Representation = 0010 0100 It considers lowest bit(at 3) and now reset rest of the bits i.e. 0000 0100 so result = 0100 i.e. 4 or in simple terms, the first set bit position from right is at position 3, hence 2^2=4 Input : 1032 Output : 8
The program below illustrates the java.lang.Long.lowestOneBit() function:
Lowest one bit = 8 Lowest one bit = 1
Program 2: The program below demonstrates the use of function when a negative number is passed.
Binary = 1111111111111111111111111111111111111111111111111111111111110100 Lowest one bit = 4
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:12: error: incompatible types: possible lossy conversion from double to long System.out.println("Lowest one bit = " + Long.lowestOneBit(12.34));
Program 4: When a string value is passed in argument.
prog.java:12: error: incompatible types: String cannot be converted to long System.out.println("Lowest one bit = " + Long.lowestOneBit("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.