The topic is known as two variables A and B, and an algorithm is designed to exchange the values of A and B.
"Method 1" is the most traditional, broadest and most famous method of adding a variable to the code as follows:
int a, b;
int c;
c=a;
a=b;
b=c;
"Method 2" does not add a third variable, swapping the values of A and B, the code is as follows:
int a, b;
a = a+b;
b = a-b;
a=a-b;
Analysis, set A and b the original value of A,b
执行代码 变量a 变量b
int a, b a b
a=a+b a+b b
b=a-b a+b a+b-b=a
a=a-b a+b-(b)=a+b-a=b a
"But" this method is only suitable for the integer type and so on, and can not be too large, otherwise there will be overflow.
"Method 3" bitwise operation
执行代码 变量a 变量b
a=a^b; a^b b
b=a^b; a^b a^b^b=a
a=a^b; a^b^a=b a
(异或)
"Ask" we usually use Method 1, Method 2 and Method 3 use less, also know that the following two is less than the 1th way to use a space, but the next two methods used in where?
"Answer": I have not met the use of the place. This is purely a research study that provides a variety of solutions.