1.^的特点
一个数据对另一个数据位异或两次,该数本身不变。
System.out.println(5 ^ 10 ^ 10); //5
System.out.println(5 ^ 10 ^ 5); //10
2.面试题
请自己实现两个整数变量的交换.
a.需要第三方变量,开发推荐使用这种
int x = 10;
int y = 5;
int temp;
temp = x;
x = y;
y = temp;
System.out.println("x = " + x + ",y = " + y);
b.不需要第三方变量,这种有弊端,有可能会超出int的取值范围.
int x = 10;
int y = 5;
x = x + y; //10 + 5 = 15
y = x - y; //15 - 5 = 10
x = x - y; //15 - 10 = 5
System.out.println("x = " + x + ",y = " + y);
c.不需要使用第三方变量,使用^
int x = 10;
int y = 5;
x = x ^ y; // 10 ^ 5
y = x ^ y; // 10 ^ 5 ^ 5 y = 10
x = x ^ y; // 10 ^ 5 ^ 10 x = 5
System.out.println("x = " + x + ",y = " + y);