Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two integers without using a third variable

I have an assignment in which I need to swap two integers without using third variable. I'm not sure how to do this. How would I code this?

like image 299
emerald Avatar asked Apr 27 '12 11:04

emerald


2 Answers

Yes, it's possible:

Dim var1 = 1
Dim var2 = 2
var1 = var1 + var2
var2 = var1 - var2
var1 = var1 - var2

But why do you need it? The code becomes abstruse.

like image 139
Tim Schmelter Avatar answered Oct 20 '22 01:10

Tim Schmelter


theoretically 3 ways

a = 4 , b = 5

1. Using XOR

a = a XOR b = 4 XOR 5 = 9     
b = a XOR b = 9 XOR 5 = 4
a = a XOR b = 9 XOR 4 = 5

2. Using +,-

a = a+b = 4+5 = 9     // should not overflow
b = a-b = 9-5 = 4
a = a-b = 9-4 = 5

3. Using *,/

a = a*b = 4*5 = 20    // should not overflow
b = a/b = 20/5 = 4    // should not overflow and should not be irrational number
a = a/b = 20/4 = 5    // should not overflow and should not be irrational number
like image 24
x-coder Avatar answered Oct 19 '22 23:10

x-coder