1. With the help of intermediate quantity exchange
int x = 10;
int y = 20;
int temp = x;
x = y;
y = temp;
In this method, the middle amount can be regarded as an empty cup, that is, the temp can be regarded as an empty cup.
Think of x as a cup with white wine and y as a cup with red wine
int temp = x; Pour the white wine into the empty cup. At this time, temp contains white wine and x becomes the empty cup.
x = y; Pour the red wine in y into the empty cup x. At this time, x is filled with red wine and y becomes an empty cup.
y = temp; Pour white wine into the empty glass of y. At this time, x contains red wine and y contains white wine, realizing the interchange of x and y.
2.Add, subtract and exchange values
int x = 10;
int y = 20;
x = x + y;
y = x - y;
x = x - y;
This method first finds the sum of two numbers and then subtracts them.
x = x + y; At this time, the value of x is 10+20=30;
y = x - y; At this time, x becomes 30 through the above operation, so y = 30 - 20 = 10;
x = x - y; At this time, y becomes 10 through the above operation, so x = 30 - 10 = 20; realizing the interchange of two numbers
3. Displacement operation exchange
int x = 10;
int y = 20;
x = x ^ y;
y = x ^ y;
x = x ^ y;