Given a number, find the index/position of its rightmost set bit. The indexing is from right to left, where the rightmost bit position starts from 1.
14
2
Note: The value of
14
in binary form is1110
. The rightmost set bit position is2
.
15
1
Note: The value of
15
in binary form is1111
. The rightmost set bit position is1
, meaning 1111
.
The steps of the algorithm are as follows:
n
.n
.All the steps above can be skipped if the number is odd as odd numbers always have the rightmost bit/LSB set or 1
.
n
To unset the rightmost bit of number n
:
n
. The idea is that when we subtract one from an integer, all the bits following the rightmost set bits are inverted, turning 1 to 0 and 0 to 1.AND
(&) operation on the result of step 1 and n
.Code wise: n & (n - 1)
Let’s see an example:
Consider n = 18,
Operation | Result |
---|---|
18 | 10010 |
18 - 1 = 17 | 10001 |
18 & 17 (n & (n - 1) ) |
10000 |
As we can see, the result of (n & (n - 1)
) is 10000
.
n
Now we XOR the result from step 1 with n
itself. This step results in the rightmost set bit in n
the only set bit.
Continuing the example above:
(n & (n - 1)
) ^ n
= 10000
^ 10010
= 00010
.
The result from step 2 is 00010
. In order to find the position of the only set bit, we can do it in two ways.
public class Main {static int findOnlySetBitPos(int n){return (int)((Math.log10(n)) / Math.log10(2)) + 1;}static int positionOfRightmostSetBit(int num){if((num & 1) != 0) return 1;// Step 1int andOp = num & (num - 1);// Step 2int xorOp = num ^ andOp;// Step 3return findOnlySetBitPos(xorOp);}public static void main(String[] args) {int num = 18;System.out.println("Position of the rightmost set bit of " + num + " is " + positionOfRightmostSetBit(num));num = 7;System.out.println("Position of the rightmost set bit of " + num + " is " + positionOfRightmostSetBit(num));}}
findOnlySetBitPos()
method. It returns the position of the only set bit.positionOfRightmostSetBit()
method. It implements the solution above to return the position of the rightmost set bit.main()
method where positionOfRightmostSetBit()
is invoked for different n
values.