First of all, you can make your original method work even in the presence of integer overflow (as long as n
fits in an int
).
As to the XOR method, observe that R1 xor M == R2
(where M
is the missing number). From this it follows that R1 xor M xor R2 == 0
and therefore M == R1 xor R2
.