r/programmingchallenges • u/mindlessCoder • Sep 15 '18
Find maximum xor
I was asked this question in an interview. Given three numbers L, R, X. We have to find a number Y such that Y⊕X is maximum and Y lies between L and R (both inclusive). One way is to use brute force and check all numbers from L to R but can we do better than this?
8
Upvotes
View all comments
Show parent comment
1
u/colurophobia Sep 16 '18 edited Sep 16 '18
What if there's no such element in that range?
Of course, if X&Y==0, X xor Y is the largest integer you can represent (all 1s) but the maximum inside the given range might not be the maximum possible ever..
Moreover, if you simply want X&Y ==0 you can just set Y=!X
I think instead of simply breaking upon finding the perfect score you need to find the actual maximum, keeping track of the current best or use some more complex heuristic, not sure about which though
Edit: the obvious counterexample is when L=R= a number that has a bit in common with X, your algorithm would not output the correct answer, but there may be some other cases, when I get back home I'll think more about it maybe
Edit2: ok I got a better counterexample. X=7, L=3, R=5.
7&3 = 3
7&4 = 4
7&5 = 5
But,
7 xor 3 = 4
7 xor 4 = 3
7 xor 5 = 2
So yeah, there are non trivial cases where you will need more or smarter computations..