I have an alternative to the xor trick that doesn't suffer from zeros.
def swap(a,b):
a=a-b
b=a+b
a=b-a
return a,b def swap(a,b):
a=a-b
b=a+b
a=b-a
return a,bNote that the problem is not that a and b have the same value, or even that one of them is 0, it's that a and b alias to the same memory location, effectively being two handles to the same variable.
In particular you can solve the problem in this article by just subtracting the numbers from 1+2+...+n-1+n. The remainder will be your missing number (though be careful with the 1+2+...+n-1+n = n(n-1)/2 formula; division by 2 is very much not compatible with arithmetic modulo a power of 2, so divide first then multiply, or keep a running total if you want to be flexible).
def swap(a, b):
return b, a
?Or since this is presumably python, just inline it without a function:
(a, b) = (b, a)