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
For Python, this will work for negative integers as well, since the mod operator always returns a positive integer. For other languages, make sure you make appropriate changes to the xor() function. Until next time...
Comments
Post a Comment