Search code examples
algorithmbit-manipulationxor

xor the two numbers in place swap?


I came across a question with swapping two numbers using xor. so the it's basically x=x^y; y=x^y; x=x^y, and i can think of y=(x^y)^y=x,so that y now becomes x, but on the last one wouldn't it bex=x^y = (x^y)^(x^y)= 0? how does x become y?


Solution

  • x=x^y
    y=(x^y)^y
    x=(x^y)^((x^y)^y) //here is how you get x = y
    

    you did the substitution wrong.