# Maximizing XOR

# Maximizing XOR

RodneyShag + 0 comments ### Java solution - more efficient than Editorial solution

import java.util.Scanner; public class Solution { public static void main(String [] args) { Scanner scan = new Scanner(System.in); int L = scan.nextInt(); int R = scan.nextInt(); scan.close(); int xored = L ^ R; int significantBit = 31 - Integer.numberOfLeadingZeros(xored); int result = (1 << (significantBit + 1)) - 1; System.out.println(result); } }

To maximize A xor B, we want A and B to differ as much as possible at every bit index.

We first find the most significant bit that we can force to differ by looking at L and R.

For all of the lesser significant bits in A and B, we can always ensure that they differ and still have L <= A <= B <= R.

Our final answer will be the number represented by all 1s starting from the most significant bit that differs between A and B

### Let's try an example

L = 10111 R = 11100 _X___ <-- that's most significant differing bit 01111 <-- here's our final answer

Notice how we don't directly calculate the values of A and B.

From my HackerRank solutions.

watsaqat + 0 comments I just want to say, I wrote about 75 lines of code because I did not know about the integer bitwise operator ^. I did learn alot though doing everything from scratch :D ...

R101154 + 0 comments I'm getting a wrong answer on test case 1. I looked at the test case and when I copy and paste the test case in myself -- it works just fine. All other test cases run just fine without any errors.

I believe there is something wrong with the test.

NoNo2 + 0 comments Question should be with strict time limit

Hiba007 + 0 comments Just One Line

return max([i^j for i in range(l, r+1) for j in range(i, r+1)])

Sort 347 Discussions, By:

Please Login in order to post a comment