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.
The Great XOR
The Great XOR
Sort by
recency
|
165 Discussions
|
Please Login in order to post a comment
Haskell
For x > 0, you can just subtract input from an equal number of "on" bits, e.g.
if x = 1010 perform: 1111 - 1010 and that's the answer.
I haven't found a really easy way (in C++) of making that 1111 number, though.
If you use the easy to code approach where you check every number, you can get the correct answer for small numbers. If you understand bits you'll be able to see that the correct answer is the invert of the original number. EX: 10 (0000 1010) - Answer: 5 (0000 0101) So what you can do is invert the bits until you reach the leftmost bit value on the original. C#:
def theGreatXor(x): list_val_bin = list(bin(x)) y = (2**(len(list_val_bin)-2))-1 return int(bin(x ^ y), 2)