Switching two numbers using only two variables

How does this happen in an exchange?

a = a + b

B = a + b

a = b + a

I do not agree that he will change the book!

Variants of the book include "complementary values ​​a and b", "deny" and "b". Hope these options are also not satisfactory.

+2
algorithm swap
Nov 18 '14 at 6:59
source share
3 answers

The deal is executed using XOR, which is usually written as a plus within the circle; eg:

a := 5 b := 7 a := a xor b (2) b := a xor b (5) a := b xor a (7) 
+5
Nov 18 '14 at 7:24
source share

The correct algorithm should be:

 a = a + bb = a - b a = a - b 
+8
Nov 18 '14 at 7:02
source share

Actually, this can be done in two ways:

 int a = 5, b = 10; 

Using addition (+) and subtraction (-)

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

Using multiple (*) and sections (/)

 a = a * b; b = a / b; a = a / b; 
0
Feb 17 '17 at 5:07 on
source share



All Articles