How do you swap two numbers without using a third variable?

Wyatt Saltzman
1 min readMay 8, 2021

TLDR

You have to store the sum of the numbers in one number and subtract the other number from the sum.

Further Explained

If i = 7 and j = 3

i = i + j; //10

j = i — j; //7

i = i — j; //3

This is a very common interview question that can be kind of tricky but has a very simple solution to it. The only issue is that this trick will not work in all conditions. There could be overflow if the added value is more than the max value of an int. This is true in languages like C/C++ but not in Java because overflows are clearly defined. Another solution that will work in most languages would be to use a bitwise and bitshift operator. An easy one to use is the XOR or exclusive or, ^.

x = x ^ y;

y = x ^ y; // now y = x

x = x ^ y; // now x = y

More Reading

--

--