Three Ways to Swap Values of Variables

1. Using intermediate variables

   That is, use a temporary variable to store the value of a variable, and then exchange the values ​​of the two variables

int a = 1;
int b = 2;
int temp = a; //1
a = b; //2
b = a; //1 

2. Addition and subtraction exchange

   That is, assign the sum of two variables to one of the variables, then subtract the value of the other variable from the value of the variable, and assign it to the other variable

int a = 1;
int b = 2;
a = a + b; //3
b = a - b; //1
a = a - b; //2

3. Use XOR operation

   The XOR operation can also be used to exchange variables. Its principle is to use the nature of the XOR operation: the result of any number XOR with itself is 0, and the result of any number XOR with 0 is itself.

int a = 1;
int b = 2;
a = a ^ b; // a = 3 ^ 2 = 1
b = a ^ b; // b = 1 ^ 2 = 3
a = a ^ b; // a = 1 ^ 3 = 2

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/130793077