The ability to exchange two-digit numbers in a program is not complicated, but if you don't use intermediate variables, you need to move your brain. This article describes two methods (in fact, the principle is one). The basic principle is the neutralization of numbers. That is, some sort of operation (two-dollar operation) converts A and b two numbers into a number and saves them in one of the variables. And then neutralize A or B with the same operator. This actually takes advantage of a or b itself as an intermediate variable.
First look at the first algorithm.
static class Num
{
int a;
int b;
}
public static void swap1(Num num)
{
num.a = num.a + num.b;
num.b = num.a - num.b;
num.a = num.a - num.b;
}
The above code assigns A and B's results to a (when a is an intermediate variable) by using the "+" operator. And then compute B, at which point the value of a is already (a+b), so a minus B is the original A. And then B is already the original A, therefore, after the operation of a (actually a+b) minus the operation of B (actually is the original a), is the original B, and finally the B assigned to a.
In fact, we can also use "*", "/" and other symbols to achieve the same effect, the code is as follows:
public static void swap2(Num num)
{
num.a = num.a * num.b;
num.b = num.a / num.b;
num.a = num.a / num.b;
}
public static void swap3(Num num)
{
num.a = num.a - num.b;
num.b = num.a + num.b;
num.a = num.b - num.a;
}
The above code has no problem in Java (but when using "/", the denominator and numerator cannot be 0). Even if the overflow will get the correct results, but in some languages (such as C), may throw overflow errors, do not avoid this error. Can be judged, the code is as follows:
public static void swap4(Num num)
{
// 不同符号
if (num.a * num.b <= 0)
{
num.a = num.a + num.b;
num.b = num.a - num.b;
num.a = num.a - num.b;
}
else
{
num.a = num.a - num.b;
num.b = num.a + num.b;
num.a = num.b - num.a;
}
}
Of course, we have a better way to use the XOR operator, and we know that any number differs from or after 0 is still itself, two the same number is different or after 0. This is the kind of feature that can have the following code.
public static void swap5(Num num)
{
num.a = num.a ^ num.b;
num.b = num.a ^ num.b;
num.a = num.a ^ num.b;
}