时间:2023-01-30 10:34:15 | 栏目:JAVA代码 | 点击:次
两数交换最简单最容易理解的就是借助第三变量
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 }
//利用php spl标准类库中的栈数据结构,先进后出实现 $a = 'abcde'; $b = 'efghi'; $stack = new SplStack(); $stack->push($a); $stack->push($b); $a = $stack->pop();//efghi $b = $stack->pop();//abcde //利用坐标轴上的两点距离数学计算 $a = 10; $b = 12; $a = $b - $a; $b = $b - $a;//10 $a = $b + $a;//12 //利用位运算中的^ $a = 10; $b = 12; $a = $a ^ $b; $b = $b ^ $a; //10 $a = $a ^ $b; //12