基操
两数交换最简单最容易理解的就是借助第三变量
public void swapOne(){ int a = 4; int b = 5; int c = a; a = b; b = c; System.out.println("a:"+a); //a:5 System.out.println("b:"+b); //a:4 }
进阶
利用数学计算
public void swapTwo(){ int a = 4; int b = 5; a=a+b; b=a-b; a=a-b; System.out.println("a:"+a); //a:5 System.out.println("b:"+b); //a:4 }
更进阶
利用异或运算
public void swapThree(){ int a = 4; int b = 5; a = a ^ b; // 0101 ^ 0100 ===> 0001,此时a的值为1 b = a ^ b; // 0001 ^ 0100 ===> 0101,此时b的值为5 a = a ^ b; // 0001 ^ 0101 ===> 0100,此时a的值为4 System.out.println("a:"+a); //a:5 System.out.println("b:"+b); //a:4 }