8

I have to swap two variables with a number value without using a third variable. What is the simple solution?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Student
  • 3,469
  • 7
  • 35
  • 42
  • 1
    possible 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 Answers6

20

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

Student
  • 3,469
  • 7
  • 35
  • 42
14

You can achieve it with XOR

int A = ...;
int B = ...;
A = A ^ B;
B = A ^ B;
A = A ^ B;
Fede
  • 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
6

Depending on the type of variable, you can use Interlocked.Exchange. This uses an atomic operation to do the swap.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
4
 int x = 15;
 int y = 5;

 x = x + y;
 y = x - y;
 x = x - y; 
MBU
  • 4,998
  • 12
  • 59
  • 98
2

Another popular way is the XOR swapping strategy. http://en.wikipedia.org/wiki/XOR_swap_algorithm

WorldIsRound
  • 1,544
  • 10
  • 15
1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jakob Alexander Eichler
  • 2,988
  • 3
  • 33
  • 49