lowestOneBit()
method?The lowestOneBit()
method of the Integer
class is a static method used to calculate an integer value with no more than a single one-bit, in the lowest-order (“rightmost”) one-bit of the supplied int
value.
The method returns zero
if the supplied value’s two’s complement binary representation has no one-bits, i.e., if it is equal to zero.
public static int lowestOneBit(int i)
int i
: This parameter holds the minimum one-bit value that must be calculated.The method lowestOneBit()
returns the single one-bit int
value in the lowest-order one-bit of the provided value, or zero
if the specified value is zero.
Let’s understand the implementation of lowestOneBit()
with the help of an example.
int value = 123
1111011
.The lowest one-bit of the 123 in its binary representation is at position 0
, the rightmost one-bit, i.e., zero-based indexing from the rightmost bit.
Now, the lowest one-bit value can be calculated using the below formula.
lowest-one-bit-value = 2 to the power of (index of the rightmost one-bit)
The lowest one-bit value for 123
is 2 ** 0 = 1
int value: 12
.
Binary representation of 12: 1100
.
Rightmost one-bit position of 1
: 2.
Int value of the rightmost one-bit: 2 ** 2 = 4
.
In the code below, we use the lowestOneBit
method on different integer values.
public class Main{private static void lowestOneBit(int number){System.out.println("Binary Representation of " + number + " - " + Integer.toBinaryString(number));System.out.println("Lowest One bit integer of " + number + " - "+ Integer.lowestOneBit(number));}public static void main(String[] args){lowestOneBit(123);System.out.println("----------");lowestOneBit(0);System.out.println("----------");lowestOneBit(12);}}