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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With