Problem : Given two integers a and b (a <= b ). Find the value of a ^ (a+1) ^ ... (b-1) ^ b. (^ is the xor operator).
This will be a short post. It's pretty trivial once you understand the pattern. I'd first refer you to this post first. In the alternate solutions, I've described how you can obtain the value of 1 ^ 2 ^ 3 .... ^ N.
Therefore, our solution simply applies that concept.
xor(b) ^ xor(a - 1) where xor function is implemented in Python as follows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def xor(N): | |
return [N,1,N+1,0][N%4] | |
def xor2(a,b): | |
return xor(b) ^ xor(a - 1) |
Comments
Post a Comment