Source: http://www.javaeye.com/topic/645596
If you do not use the third variable to exchange two integers, you may have encountered this question. For example:
JavaCode
Public Class Person {
Public Static Void Main (string [] ARGs ){
// Use addition and subtraction
Int A = 10 , B = 5 ;
A = A + B;
B = A - B;
A = A - B;
System. Out. println ( " A = " + A + " \ NB = " + B );
}
}
There is another method that is more efficient:
Java code
Public Class Person {
Public Static Void Main (string [] ARGs ){
// The exchange rate is met by using a number-exclusive or equal to 0 and exclusive operations.
Int A = 10 , B = 5 ;
A = A ^ B;
B = A ^ B;
A = A ^ B;
System. Out. println ( " A = " + A + " \ NB = " + B );
}
}
Of course, the above two typesAlgorithmThe corresponding js also supports the following:
JS Code
VaR A = 11 , B = 22 ;
A = A + B;
B = A - B;
A = A - B;
Console. Log ( + ' \ N ' + B)
Or
JS Code
VaR A = 11 , B = 22 ;
A = A ^ B;
B = A ^ B;
A = A ^ B;
Console. Log ( + ' \ N ' + B)
However, if two variables are of the object type, Java (strong type) seems powerless. But JS works. There are still many implementation methods, such:
JS Code
VaR A = {Name: ' Jack ' }, B = {Name: ' Tom ' };
A = [A, B];
B = A [ 0 ];
A = A [ 1 ];
Console. Log (A. Name + ' \ N ' + B. Name)
Or
JS Code
VaR A = {Name: ' Jack ' }, B = {Name: ' Tom ' };
A = {A: A, B: B };
B = A.;
A = A. B;
Console. Log (A. Name + ' \ N ' + B. Name)
It is precisely the use of JS dynamic (weak type) systems and direct object/array features. Other strong types are not allowed. The compiler will prompt a type conversion error.
Http://en.wikipedia.org/wiki/XOR_swap Resources