本帖最后由 hacket 于 2013-3-24 10:05 编辑
- package q_2013_03_23;
- public class SwapDemo {
- public static void main(String[] args) {
-
- // 两个数交换
- swap5(3,5);
-
- }
- // 第三方临时变量-temp
- public static void swap1(int a,int b){
-
- System.out.println("a="+a+":"+"b="+b);
- int temp;
- temp = a;
- a = b;
- b = temp;
- System.out.println("a="+a+":"+"b="+b);
- }
- // 不用第三方临时变量-用加减-多行代码
- public static void swap2(int a,int b){//a=3 b=5
- System.out.println("a="+a+":"+"b="+b);
- a = a + b;// a=a+b=3+5=8, b=b=5
- b = a - b;// b=8-5=3
- a = a - b;// a=8-3=5
- System.out.println("a="+a+":"+"b="+b);
- }
- //不用第三方临时变量-异或-效率高
- public static void swap3(int a,int b){//a=3 b=5 a=00000011 b=00000101
- System.out.println("a="+a+":"+"b="+b);
- a = a ^ b;//a = 00000110,b=00000101
- b = a ^ b;//b = 00000011=3, a = 00000110
- a = a ^ b;//a = 00000101=5
- System.out.println("a="+a+":"+"b="+b);
- }
- //用一行代码实现交换,用加减
- public static void swap4(int a,int b){
- System.out.println("a="+a+":"+"b="+b);
- b=a+b-(a=b);//b=3-(a=2)=1 //用一行代码实现交换
- //或者a=b+a-(b=a);
- System.out.println("a="+a+":"+"b="+b);
- }
- //用一行代码实现,异或
- public static void swap5(int a,int b){//a=3,b=5
- System.out.println("a="+a+":"+"b="+b);
- a = a^b^(b=a);//a=5,b=3
- System.out.println("a="+a+":"+"b="+b);
- b = b^a^(a=b);
- System.out.println("a="+a+":"+"b="+b);
- }
-
-
-
- }
复制代码
本人总结的关于两个数交换的几种方法,要是还有其他好的方法,可以分享一下。
|
|