How to exchange two values without using an extra variable ------- bitwise exclusive or operation, variable -------
Problem: Generally, we need to exchange the values of two variables. We usually adopt an additional variable, for example, temp = a, a = B, B = temp, can we exchange the values of a and B without using temp?
Solution: ^ exclusive or operator, and we will find that a ^ a = 0 and 0 ^ a = a. Based on these two theories, we can implement the problem we raised earlier.
The Code is as follows:
# Include <stdio. h>
Void inplace_swap (int * x, int * y)
{
* Y = * x ^ * y;
* X = * x ^ * y;
* Y = * y ^ * x;
}
Int main ()
{
Int a = 3, B = 4;
Printf ("before exchange: a = % d, B = % d \ n", a, B );
Inplace_swap (& a, & B );
Printf ("value after exchange: a = % d, B = % d \ n", a, B );
Return 0;
}
Note: first, * y = * x ^ * y. At this time, a = a, B = a ^ B
In addition, * x = * x ^ * y. At this time, a = a ^ B. The two formulas above are used: a ^ B = 0 ^ B = B. At this time, a = B, B = a ^ B
Finally, * y = * y ^ * x B = a ^ B, same as above, B = a ^ 0 = a; in this way, a is switched, B value.