Maximum XOR : DP Bitmask

I am not able to access the editorial. Can you please share the tutorial of the questin ? Thank you.

Maximum XOR

Given two integers l and r , your task is to find the maximum xor of two integers both of which lying between l and r inclusive.
Input Format

The first line contains l and r separated by a space.
Constraints

l, r<=10^18
Output Format

Output is a single number denoting the maximum xor
Sample Input

79242383109441603 533369389165030783

Sample Output

576460752303423487

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

I didn’t understood the use of " if ((((l>>poz)^(r>>poz))&1LL)==1LL) ret += br;" as given in the editorial. What is this condition doing ? Can you please explain ?

I mean what is the basic idea behind approaching this problem ?

An efficient solution is to consider pattern of binary values from L to R. We can see that first bit from L to R either changes from 0 to 1 or it stays 1 i.e. if we take the XOR of any two numbers for maximum value their first bit will be fixed which will be same as first bit of XOR of L and R itself.
After observing the technique to get first bit, we can see that if we XOR L and R, the most significant bit of this XOR will tell us the maximum value we can achieve i.e. let XOR of L and R is 1xxx where x can be 0 or 1 then maximum XOR value we can get is 1111 because from L to R we have all possible combination of xxx and it is always possible to choose these bits in such a way from two numbers such that their XOR becomes all 1. It is explained below with some examples,
int maxXORInRange( int L, int R)

{

// get xor of limits

int LXR = L ^ R;

// loop to get msb position of L^R

int msbPos = 0;

while (LXR)

{

msbPos++;

LXR >>= 1;

}

// construct result by adding 1,

// msbPos times

int maxXOR = 0;

    int two  =1;

while (msbPos--)

{

maxXOR += two;

two <<= 1;

}

return maxXOR;

}

so basically, get the position of the most significant bit of L^R
now, add 1 for each position of the position obtained

why this actually works is quite simple, if a state has been reached of 1xxx in L^R there must definitely be an intermediate state of 1111

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.