- "^" 位逻辑运算符
class ysf {
public static void main(String[] args) {
System.out.println(5 ^ 10 ^ 10);
System.out.println(5 ^ 10 ^ 5);
// "^" 的特点:一个数据对另一个数据位异或两次,该数本身不变
}
}
-
需要定义第三方变量
class ysf {
public static void main(String[] args) {
int x = 10;
int y = 5;
int temp;
temp = x;
x = y;
y = temp;
System.out.println("x = " + x + " , y = " + y );
//定义第三方变量,变量互换
}
}
- 不需要第三方变量
class ysf {
public static void main(String[] args) {
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 );
//不需要定义第三方变量,有弊端,有可能会超出int的取值范围
}
}
- 不需要定义第三方变量,通过 ^ 来做
class ysf {
public static void main(String[] args) {
int x = 10;
int y = 5;
x = x ^ y; //10 ^ 5
y = x ^ y; //10 ^ 5 y = 10
x = x ^ y; //10 ^ 5 ^ 10 x=5
System.out.println("x = " + x + " , y = " + y );
// 左边 x y x 右边都是 x ^ y
}
}