I have to swap two variables with a number value without using a third variable. What is the simple solution?
-
1possible duplicate of [Swap the values of two variables without using third variable](http://stackoverflow.com/questions/756750/swap-the-values-of-two-variables-without-using-third-variable). Also [Swap two variables without using a temp variable](http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable) – Michael Mrozek Mar 17 '11 at 20:31
-
http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable – Inisheer Mar 17 '11 at 20:32
-
@Will I've seen some use things like these as trick questions during interviews. I don't know what it's meant to *prove*, but I've seen it.. – code_dredd Jun 02 '17 at 22:18
6 Answers
Let us see one of the method namely by using arithmetic operators.
Consider 2 variables say x=50 and y=70 and let us see how to swap the value of two variables that is make x=70 and y=50 without using third variable. This can be done by using following arithmetic operations namely
x= x + y
y= x - y
x= x - y
Which gives
• x= x + y gives x= 70 + 50 an so x is equal to 120
• y= x - y gives y = 120 - 70 which makes the value of y as 50
• x= x - y gives x= 120 - 50 and thus value of x becomes 70

- 3,469
- 7
- 35
- 42
-
-
2
-
4Answer `x -= y = (x += y) - y;` and tell the teacher that's one of the lamest questions ever. – Amadan Mar 17 '11 at 20:40
-
1@Amadan Except when people use things like these as trick questions during interviews, as if that actually proved anything... :/ – code_dredd Jun 02 '17 at 22:17
You can achieve it with XOR
int A = ...;
int B = ...;
A = A ^ B;
B = A ^ B;
A = A ^ B;

- 3,928
- 1
- 20
- 28
-
@Bertrand, I just made a "mind test" and still believe it's ok. If A equals B, in the first assignment, the result of A would be 0, then B is assigned 0 XOR B which is B, and then A is assigned 0 XOR B which is B again (which was equal to the starting A). – Fede Mar 17 '11 at 20:57
-
A=1, B=1. Step 1: A=A^B=1^1=0. Step2: B=A^B=0^1=1. Step3: A=A^B=0^1=1. Looks like it works to me. – Jim Mischel Mar 17 '11 at 21:42
Depending on the type of variable, you can use Interlocked.Exchange. This uses an atomic operation to do the swap.

- 554,122
- 78
- 1,158
- 1,373
Another popular way is the XOR swapping strategy. http://en.wikipedia.org/wiki/XOR_swap_algorithm

- 1,544
- 10
- 15
Here we have this in MIPS assembler. The first solution is long and bad. The second one with XOR is better.
addi $t0, $0, -5
addi $t1, $0, 15
add $t0, $t0, $t1
sub $t1, $t1, $t0
nor $t1, $0, $t1
addi $t1, $t1, 1
sub $t0, $t0, $t1
####
xor $t0, $t0, $t1
xor $t1, $t0, $t1
xor $t0, $t0, $t1

- 30,738
- 21
- 105
- 131

- 2,988
- 3
- 33
- 49