Student
Student

Reputation: 3499

How to swap without a third variable?

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

Upvotes: 8

Views: 23247

Answers (6)

Jakob Alexander Eichler
Jakob Alexander Eichler

Reputation: 3056

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

Upvotes: 1

Fede
Fede

Reputation: 4016

You can achieve it with XOR

int A = ...;
int B = ...;
A = A ^ B;
B = A ^ B;
A = A ^ B;

Upvotes: 14

MBU
MBU

Reputation: 5098

 int x = 15;
 int y = 5;

 x = x + y;
 y = x - y;
 x = x - y; 

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564413

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

Upvotes: 6

WorldIsRound
WorldIsRound

Reputation: 1554

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

Upvotes: 2

Student
Student

Reputation: 3499

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

Upvotes: 20

Related Questions