We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Strip your number down to the most significant bit followed by some amount of 0s or 1s thereafter. This can be done using l^r. The first time one of the numbers has a 1 and the other doesn't, this will be your most significant bit.

Set all the following 0s to 1s. If 1000 is your most significant, the maximum will be 1111.

Print the decimal interpretation of the resulting binary number.

8 is 1000 and 7 is 0111. Anything between 8 and 0 is going to be 15 because your highest XOR number is 1111. As you can see, you can find this by finding the most significant bit and flipping all the following to 1.

8 is 1000 and 9 is 1001. Here you'll find that the answer is 0001. This is because 8 and 9 share the same most significant bit. So after XOR the most significant bit is 0001.

27 is 11011 and 8 is 01000. Here your MSB is 10000 and you can choose 10111 and 01000.

I wish I could explain it better but it's easiest to notice the pattern and go from there. Every answer will always be a power of 2 minus 1, so every answer is always a series of 1s.

## Maximizing XOR

You are viewing a single comment's thread. Return to all comments →

sir can you explain how the below solution is solving this problem.

def maxXOR(L,R): P = L^R ret = 1 while(P): # this one takes (m+1) = O(logR) steps ret <<= 1 P >>= 1 return (ret - 1)

i dont understand that how we are getting right answer by doing this method.

Consider this: https://www.hackerrank.com/challenges/maximizing-xor/submissions/code/44305239

Thanks buddy for response.But can you explain why we are replacing all zeros to ones after most significant digit.

The best way I can explain it is with examples.

8 is 1000 and 7 is 0111. Anything between 8 and 0 is going to be 15 because your highest XOR number is 1111. As you can see, you can find this by finding the most significant bit and flipping all the following to 1.

8 is 1000 and 9 is 1001. Here you'll find that the answer is 0001. This is because 8 and 9 share the same most significant bit. So after XOR the most significant bit is 0001.

27 is 11011 and 8 is 01000. Here your MSB is 10000 and you can choose 10111 and 01000.

I wish I could explain it better but it's easiest to notice the pattern and go from there. Every answer will always be a power of 2 minus 1, so every answer is always a series of 1s.