Given a number, we’ll find the index/position of its rightmost unset bit. The indexing is from right to left, where the rightmost bit position starts from 1.
Example 1:
In this example, 14
in binary form is 1110
. The rightmost unset bit position is 1
which is 1110.
Example 2:
-1
In this example,15
in binary form is 1111
. There aren’t set bits. Hence, the output is -1
.
The steps of the algorithm are as follows:
n
) is zero, then return 1
.-1
.NOT
on n,
which is one’s complement of n
. Now, the unset bits become set.Note: Refer to How to find the position of the rightmost set bit of an integer? to implement step 4.
Note: Refer to How to check if all bits are set in a number? to implement step 2 implementation.
class Main{static int positionOfRightmostSetBit(int n) {return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;}static int positionOfRightmostUnsetBit(int n) {if (n == 0) return 1;if ((n & (n + 1)) == 0) return -1;return positionOfRightmostSetBit(~n);}public static void main(String args[]) {int n = 14;System.out.print("The position of rightmost unset bit of " + n + " is " + positionOfRightmostUnsetBit(n));}}
positionOfRightmostSetBit()
method that returns the position of the rightmost set bit.positionOfRightmostUnsetBit()
method to implement the above solution to find the rightmost unset bit of the number.n
.positionOfRightmostSetBit()
with n
.