简体   繁体   中英

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?

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.

Lets assume

a = 10; 
b = 20; 

a = a + b; // a = 30

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

Values swapped.

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
 Dim a As Integer
 Dim b As Integer
 a= 1
 b= 2

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

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

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

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)
    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)

Check link written for you

Approach#1.

Addition and Subtraction Method

Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;

Problem:

Incorrect result when sum of numbers will exceed the Integer range.

Approach#2.

Multiplication and Division Method

Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;

Problems:

  1. If the value of a*b exceeds the range of integer.
  2. If the value of a or b is zero then it will give wrong results.

Approach#3.

XOR Method

Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;

Best approach to solve this problem without any pitfalls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM