Do not use the third variable to exchange the values of two variables
In Java, it is often necessary to exchange the values of two variables, and we usually use the third variable to complete it.
for example:
temp = a; a = b; b = temp;
This way of writing can indeed achieve the goal, but the third variable is introduced, which increases the consumption of resources.
Here are two ways to implement without using the third variable
These two methods are only personal summary, and it cannot be concluded that there are only these three. I really hope that everyone can propose other ways to learn from each other.
Addition and subtraction exchange method
a = a + b; b = a - b; a = a - b;a = a + b; b = a - b; a = a - b;
There are more advanced writing methods in this way:
a = a + b - (b = a);
This writing method has indeed achieved the goal, but it is still a digital skill. The following is a computer underlying method.
XOR algorithm
The XOR operation is usually used less, so let me introduce it first.
Two numbers perform the exclusive OR operation, which is actually the operation of each bit of their binary number:The same is 0, the difference is 1。
0 ^ 0 = 0;1 ^ 0 = 1;0 ^ 1 = 1;1 ^ 1 = 0;
From this we can obtain 3 characteristics of XOR:
- 0 Exoor any number = any number
- 1xor any number = any number inverse
- Any number XOR itself = set yourself 0
Common uses of XOR:
- Flip certain bits
For example logarithm10100001The 2nd and 3rd bits of the00000110Perform XOR operation:
10100001 ^ 00000110 = 10100111
- Exchange of values of two variables without having to use a third variable
This is what we need here.
For example, swap two integers a =10100001,b = 00000110The value of , can be implemented like this:
a = a ^ b; // a = 10100111 b = b ^ a; // b = 10100001 a = a ^ b; // a = 00000110
The above process is equivalent to:
a = a ^ b; b = b ^ a = b ^ ( a ^ b ) = a ^ b ^ b = a ^ 0 = a; a = a ^ b = (a ^ b) ^ a = b ^ a ^ a = b ^ 0 = b;
This enables the exchange of two variable values.
This method is more recommended, not because this way is more advanced, but because such binary operations are the fastest and the execution efficiency is the highest.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.