[Interview Question] Swap the values of two variables

Swap the values ​​of two arbitrary value variables, such as:

int a=1;

int b=2;

Option 1: Use the method of adding and subtracting variables (used in interviews)

a = a + b;

b = a - b;

a = a - b;

Option 2: Adding and subtracting variables to assign values ​​(used in interviews)

b = (a + b) - (a = b);

Option 3: Realize with the characteristics of XOR (used in interviews)

a = a ^ b;

b = a ^ b;//a ^ b ^ b = a

a = a ^ b;//a ^ b ^ a = b

Option 4: Use third-party variables (used in development)

int c = a;

a = b;

b = c;

In fact, this is a question that can only be used to fool people during an interview, and it doesn't have much practical meaning! First of all, we must emphasize that the variable type must be an integral type, and there is almost no such idiotic question in actual development! What makes people feel even more absurd is that some people don't let you use the third variable in order to add a little bit of mystery, but a lot of logic in actual development is realized by the third variable!

Original link: https://www.xubingtao.cn/?p=3411

Follow my public account to release all kinds of useful information for you every day.

For more information, please visit my other side:

Guess you like

Origin blog.csdn.net/xubingtao/article/details/114117897