emerald
emerald

Reputation: 329

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?

Upvotes: 10

Views: 20874

Answers (8)

x-coder
x-coder

Reputation: 101

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

Upvotes: 1

ras123
ras123

Reputation: 1

    Take two text boxes and a command box.In command box type this code.  
    text1.text=val(text1.text) + val(text2.text)      
    text2.text=val(text1.text) - val(text2.text)  
    text1.text=val(text1.text) - val(text2.text)

Upvotes: 0

Jainendra
Jainendra

Reputation: 25143

To swap two numeric variables do like this

a = a + b;
b = a - b;
a = a - b;

OR

a = a xor b;
b = a xor b;
a = a xor b;

where a and b are variables to be swapped

Upvotes: 2

Paul Grimshaw
Paul Grimshaw

Reputation: 21024

Lets assume

a = 10; 
b = 20; 

a = a + b; // a = 30

b = a - b; // b = 10
a = a - b; // a = 20

Values swapped.

Upvotes: 7

APrough
APrough

Reputation: 2701

The Xor or a+b algorithms above work and are the best way to do this, but just an example of a weird way to do it. Still not sure why you would want to do this. Just build a function that you supply two values ByRef and have it do the standard swap method.

Dim newList as New List(Of Integer)
newList.Add firstvalue
newList.Add secondValue
newList.Reverse
secondValue = newList.Item(0)
firstValue = newList.Item(1)

Upvotes: 0

Prashanth Thurairatnam
Prashanth Thurairatnam

Reputation: 4361

 Dim a As Integer
 Dim b As Integer
 a= 1
 b= 2

 a = a Xor b
 b = a Xor b
 a = a Xor b

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460068

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.

Upvotes: 19

jon
jon

Reputation: 6246

Read up on the "xor swap algorithm."

You can find an answer here:

http://www.java2s.com/Tutorial/VB/0040__Data-Type/Swaptwointegerswithoutusingathird.htm

firstValue = firstValue Xor secondValue
secondValue = firstValue Xor secondValue
firstValue = firstValue Xor secondValue

Upvotes: 5

Related Questions