In the process of software development, it is often necessary to exchange the values of the two variables. There are three ways we can use the interchange method.
The first method:
int a = 3, b = 4;
int tmp;
TMP = A;
A = b;
b = tmp;
This approach is often used by the use of third variables.
The advantage is that readability is strong.
The disadvantage is that the introduction of third-party variables, high memory consumption.
The second method:
int a = 3, b = 4;
A = a + B; A = 7; The principle is to use two numbers and a + b = Sum
b = a A; b = 7-4 = 3 B = sum-b
A = a-B; A = 7-3 = 4; A = Sum-b
The drawback of this approach is that if the values of the two variables are very large, it will cause two variables and overflow.
The advantage is that no third-party variables are introduced to save memory.
The disadvantage is that there is a risk of data overflow, and the readability is not strong.
The third method:
int a = 3, b = 4;
A = a ^ b; The principle is to use the XOR operator
b = a ^ b; b = a ^ b ^ b = A A ^ a = 0, b ^ 0 = b
A = a ^ b; A = a ^ b ^ a = a ^ a ^ b
The advantages of this method are: No third-party variables are introduced, and memory space is saved;
There is no problem of data overflow;
The disadvantage is: The skill is strong, the readability is poor.
This article is from the "FAI Aberdeen" blog, please make sure to keep this source http://weiguozhihui.blog.51cto.com/3060615/1650435
Several ways to swap the values in two variables