Given two numbers, x
and y
, find the position of the rightmost different bit of the two numbers.
Example 1:
x=11
, y=9
11 - 1011
9 - 1001
The second rightmost bit is different, hence, the answer is 2
.
We’ll use bitwise XOR and find the position of the rightmost set bit.
The steps involved in the solution are as follows:
x
and y
. Here, the different bits of x
and y
become set in x ^ y. If the numbers are identical, then the XOR will be zero, and there will be no different bit.Example of the algorithm:
The position of the rightmost set of bits is 2.
Let’s look at the code below:
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 x = 11;int y = 9;int xorOp = x ^ y;if(xorOp == 0)System.out.println("The numbers are same");else{int pos = positionOfRightmostSetBit(xorOp);System.out.println("The position of the rightmost different bit of " + x + " and " + y + " is " + pos);}}}
findOnlySetBitPos()
is defined that returns the position of the only set bit.positionOfRightmostSetBit()
method is defined that implements the solution above to return the position of the rightmost set bit.x
.y
.x
and y
.