方法1:
int a = 1;
int b = 2;
//交换
a = a + b;
b = a - b;
a = a - b;
Console.WriteLine("a={0} b={1}", a, b);
方法2:
int a = 1;
int b = 2;
//交换
a=a^b;
b=b^a;
a=a^b;
Console.WriteLine("a={0} b={1}", a, b);
证明:
a1=a0^b0;
b1=b0^a1=b0^(a0^b0)=a0^b0^b0=a0;
a2=a1^b1=(a0^b0)^a0=b0^a0^a0=b0;
原理:
一个值经过同一个数的两次异或后值不变。