Interview questions without using the third variable, exchange the values of two numbers

For example, a=10, b=20, the values ​​of the two of them are required to be exchanged, and the third variable cannot be used

The first method: addition and subtraction

#include <stdio.h>
int main()
{
    
    
int a=10;
int b=20;
printf("交换前:a=%d     b=%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("交换后:a=%d     b=%d\n",a,b);
system("pause");
return 0;
}

This completes the exchange of a and b, but we still have a better method, which is the
second method: exclusive OR method

#include <stdio.h>
#include <stdlib.h>
int main()
{
    
    
int a=10;
int b=20;
printf("交换前:a=%d     b=%d\n",a,b);
a=a^b;
b=a^b;
a=a^b;
printf("交换后:a=%d     b=%d\n",a,b);
system("pause");
return 0;

Insert picture description here

Temporarily store the XOR value of a and b in a, and let b XOR the XOR value of a and b to get the original a. At this time, b=the original a. We then let a XOR a and You can get b by XOR of b, thank you for watching.

Guess you like

Origin blog.csdn.net/weixin_54748281/article/details/113767717