For the exchange of two variables, I found four methods, below I use Java to illustrate.
1. Use the third variable to exchange values, a simple method.
Class Testev
Create a class
{
public static void Main (String[]args)
{
int x =5,y=10; Define two variables
int temp = x; Define the third Temp variable temp and extract the X value
x = y; Assign the value of Y to X
y = temp; Then assign the temporary variable temp value to Y
System.out.println ("x=" +x+ "y=" +y);
}
}
2. It is possible to exchange data in the same way that two numbers are summed and subtracted, and the disadvantage is that if the values of x and Y are too large, the value exceeding int will lose precision.
Class testev//Create a classes {public static void main (String[]args) {int x =5,y=10;//define two variables x = x + y ; X (All) = 5 + ten; y = x-y; Y (5) = x (15)-10; x = XY; X (Ten) = X (All)-Y (5) System.out.println ("x=" +x+ "y=" +y); } }
3. The use of bit operations to exchange data, The thought principle used is: a number of different or the same number two times, the result is the number , and will not exceed the int range
Class Testev
Create a class
{
public static void Main (String[]args)
{
int x =5,y=10; Define two variables
x = X^y;
y = x^y; Y= (x^y) ^y
x = X^y; x= (x^y) ^x
System.out.println ("x=" +x+ "y=" +y);
}
}
4. Simplest, swap variables directly at the time of printout
Class Testev
Create a class
{
public static void Main (String[]args)
{
int x =5,y=10; Define two variables
System.out.println ("x=" +y+ "y=" +x); Exchange directly at the time of output
}
}
From for notes (Wiz)
Four ways to exchange two variables