1、位异或运算符^
的特点:一个数据对另一个数据位异或两次,该数本身不变。
System.out.println(5 ^ 10 ^ 10); //输出5
System.out.println(5 ^ 10 ^ 5); //输出10
2、面试题:请实现两个整数变量的交换(不需要定义第三方变量)。
int x = 5;
int y = 10;
1)我们先来使用第三方变量来实现:【开发时推荐使用】
int temp;
temp = x;
x = y;
y = temp;
System.out.println("x = " + x + ", y =" + "y"); //x = 10,y = 5
2)不需要第三方变量来实现:【弊端:如果x、y相加以后超出了int的取值范围,那么结果就会出错】
x = x + y;
y = x - y;
x = x - y;
System.out.println("x = " + x + ", y =" + "y"); //x = 10,y = 5
3)不需要第三方变量,通过亦或来实现:
x = x ^ y; // x = 10 ^ 5
y = x ^ y; // y = 10 ^ 5 ^ 5 = 10
x = x ^ y; // x = 10 ^ 5 ^ 10 = 5
System.out.println("x = " + x + ", y =" + "y"); //x = 10,y = 5
左边是x
,y
,x
,右边都是x ^ y