Swap two integers in different ways

104 Views Asked by At

This is a famous rudimentary problem : how to use mathematical operations (not any other temporary variable or storage) to swap two integers A and B. The most well-known way is the following:

A = A + B
B = A - B
A = A - B

What are some of the alternative set of operations to achieve this?

2

There are 2 best solutions below

0
On

I'm not sure if you're asking for all solutions or not, but one of the most famous solutions is by using binary xor three times. $A=A\oplus B,B=A\oplus B,A=A\oplus B$.

0
On

Any group operator — that is, any operator that is associative and has an identity and inverse — provides a solution to this problem. Suppose that the operator is $\bigtriangleup$, and that every element $X$ has an inverse $X^{-1}$ such that $X\bigtriangleup X^{-1} = X^{-1}\bigtriangleup X = e_{\triangle}$ for all $X$, where $e_\triangle$ is the identity for the $\bigtriangleup$ operator: $Y\bigtriangleup e_\triangle = e_\triangle\bigtriangleup Y = Y$ for all $Y$. Then starting with $A=A_0$, $B=B_0$ the sequence of operations $$\begin{align}A&=A\bigtriangleup B\\ B&=A\bigtriangleup B^{-1}\\ A&=B^{-1}\bigtriangleup A\end{align}$$ successively sets $A=A_0\bigtriangleup B_0$, then $B=(A_0\bigtriangleup B_0)\bigtriangleup B^{-1}_0$ $=A_0\bigtriangleup (B_0\bigtriangleup B^{-1}_0)$ $= A_0$, and finally $A=A_0^{-1}\bigtriangleup (A_0\bigtriangleup B_0)$ $= (A_0\bigtriangleup A_0^{-1})\bigtriangleup B_0$ $= B_0$. Note that associativity is used in both the second and third operations. This approach also requires an 'easy' way of writing the inverse operation.

All of the 'classic' examples (the addition/subtraction version that you give, as well as the XOR version) can be seen as examples of this general scheme; in the case of addition and subtraction the $B=A\bigtriangleup B^{-1}$ step can be written as $B=A+(-B) = A-B$, and using the commutativity of addition the $A=B^{-1}\bigtriangleup A$ step can be written as $A=(-B)+A = A+(-B) = A-B$. In the case of XOR, $A$ and $B$ are their own inverses, and the operation is again commutative, so we get the $A=A\bigoplus B,\ B=A\bigoplus B,\ A=A\bigoplus B$ solution.