方法一:利用异或,一个数以后另一个数两次,值不变.
x1 = x1 ^ x2; //x1 = x1 ^ x2
x2 = x1 ^ x2; //x2 = (x1 ^ x2) ^ x2 ,所以,x2 = x1
x1 = x1 ^ x2; //x1 = (x1 ^ x2) ^ x2(x2的值为x1) ,相当于x1 =(x1 ^ x2) ^(x1) = x2;
方法二:加减
x1 = x1 + x2; // x1 = x1 + x2
x2 = x1 - x2; // x2 = (x1 + x2) - x2,所以,x2 = x1
x1 = x1 - x2; // x1 =(x1 + x2) - x2(此时的x2,已经是x1啦),即x1 = (x1 + x2) - x1 = x2;
方法三:是最简单,也是最常用的,临时变量法
int temp;
temp = x1;
x1 = x2;
x2 = temp; |
|