XOR Profit Problem

Please share optimised code for this problem.

XOR gives 0 when 1,1 or 0,0 are taken. Also it gives 1 when 1,0 or 0,1 are taken.

So we need to observe that XOR of 2 nos. will be maximum if the XOR only contains 1s. We can find the most significant bit position and then put 1s to all the places up to it in binary form. Then convert the binary into decimal. Upon doing some math we can see that the final no. will come as (2 to the power n) - 1, where n is the position of most significant bit indexing starting from 1.

Below is the CPP code implementation of what I said :

#include

#include<math.h>

using namespace std;

int main () {

int x,y;

cin>>x>>y;

int xr = x^y;

int msb = 0;

while(xr)

{

msb++;

xr = xr >> 1;

}

int ans = pow(2,msb) - 1;

cout<<ans<<endl;

return 0;

}

I hope your doubt is resolved.
Please rate your experience and feel free to reach out to me again if still further doubts.

So two things are always true:-

  1. xor of x and y gives us most significant bit position.
  2. there exist two numbers between x and y, such that xor of those two numbers give us all setbits till the position of most significant bit.

Is this right?