交换两变量的值,不使用第三变量
public class Test2 {
public static void main(String[] args) {
//不借助中间变量交换a与b的值
int a = 1;
int b = 2;
//1、数值相加交换(溢出风险)
a = a + b;
b = a - b;
a = a - b;
System.out.println(a);
System.out.println(b);
System.out.println("----------------");
//2、数值相减交换(溢出风险)
a = a - b;
b = b + a;
a = b - a;
System.out.println(a);
System.out.println(b);
System.out.println("----------------");
//3、利用语法特性交换(本质使用了第三变量)
b = a + (a = b) * 0;
System.out.println(a);
System.out.println(b);
System.out.println("----------------");
//4、异或运算交换(完美解法)
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a);
System.out.println(b);
a = a ^ b ^ b;//异或运算原理
System.out.println(a);
}
}