A , B when two variables exchange their values, the most basic practice is to find an intermediate variable for temporary storage, just as there are two water cups, A, B the simplest way to change the water volume of two milliliters of water cups is to find an intermediate cup. C put a cup ( assume that A) the water in is saved in it. Then, set B pour water from the cup to the Cup A . C down to A .
ExchangeA, BFor the values in the two variables, you can find an intermediate variable.CSave:
C = A; A = B; B = C;
Although this completes the task, a variable is used. So how can we do this without the third variable? This is a common method:
A = a + B; B = A-B; A = A-B;
In this way, the intermediate variable is saved to realize the exchange of two variable values.
Today, I suddenly thought of the third approach:
A = a xor B; B = a xor B; A = a xor B;
UseCLanguage:
A ^ = B; B ^ = A; A ^ = B;
What is better than the second method above is that there will be no overflow. It is fast, and it is the fastest for anyone to execute bitwise operations on the computer.
Of course, the third method can be used because the XOR operator satisfies the combination and exchange laws. There are also properties a ^ A = 0; a ^ 0 =;