The usual procedure for exchanging two variables, A/b, is
int temp;
Temp=a
A=b;
B=temp;
the 3rd temporary variable temp above is required .
Using the following method, for a given two integers a, a, the following XOR operation can achieve A/b exchange without the help of the 3rd temporary variable:
A = a ^ b;
b = a ^ b;
A = a ^ b;
This exchange of two variables without the help of the 3rd temporary variable process, the implementation is mainly based on the following properties of the XOR operation:
1. Any one of the variable X and its own XOR operation, the result is 0, that is, x^x=0
2. any one of the variables X and 0 is an XOR operation, the result is unchanged, that is, x^0=x
3. The XOR operation has the binding, namely a^b^c= (a^b) ^c=a^ (b^c)
4. The XOR operation is exchangeable, i.e. A^b=b^a
Analysis:
First step: a = a ^ b;
The result of a variable after completion is a ^ b
Step Two: b = a ^ b;
At this point, a to the right of the assignment number is the value of a ^ B, then the assignment number to the right of a with a ^ B replaced,
Get (a ^ b) ^ B=a ^ (b ^ b) =a ^0=a,
That is, after the second operation, the value in B is a, which is b=a, and a is changed to B.
Step three: a = a ^ b;
At this time the assignment number to the right of a save is still a ^ B value, and the assignment number to the right of B is already a,
Replace the assignment number to the right of the B, respectively,
That is, the assignment number to the right a ^ b= (a ^ b) ^ A=a ^ b^ a=a ^ a^ b=0^ b=b, the value assigned to a, that is a=b
That is, after the third operation, the value in A is B, which is a=b, and B is changed to a.
This completes the exchange of two variables, a, B, as in the three steps above, without the need for a 3rd temporary variable procedure.
This process is equivalent to the following process:
A=a+b
B=a-b;
A=a-b;
The precondition is that the value of the a+b cannot overflow.
XOR Exchange Variable