Suppose you have two variables, a and b. How can you swap their values without using a temporary variable and also without using the bitwise operator XOR?
In a similar manner to the XOR solution, we can use simple addition and subtraction:
a = a + b;
b = a - b;
a = a - b;
Comments
Now, can you think about swapping 3 variables(for ex. input,a=5,b=10,c=15 then output, a=15,b=5 and c=10) applying same rules as in this question
Using the method above, swap a and c first and then swap b and c
solution: a=a+b; b=a-b; a=a-b; example: a=2,b=3 a=2+3; (a=5) b=5-3; (b=2) a=5-2; (a=3) now a=3,b=2
Can also be done as:
NOTE: does not work if a or b is 0
a = a+b b = a-b a = a-b
Example: a = 7 b = 3
Example: a = 7+3 = 10 b = 10-3 = 7 a = 10-7= 3
Yep, that's exactly the solution provided.