- public static void main(String[] args) {
- int a=5;
- int b=3;//利用第三方变量
- int temp;
- System.out.println("交换前:"+a+","+b);
- temp=a;
- a=b;
- b=temp;
- System.out.println("第一种交换方式");
- System.out.println("交换后:"+a+","+b);
- count();
- }
-
- static void count(){
- int a=5;//利用加减法实现两个变量的交换,
- int b=3;
- System.out.println("\n交换前:"+a+","+b);
- a=a+b;
- b=a-b;
- a=a-b;
- System.out.println("第二种交换方式");
- System.out.println("交换后:"+a+","+b);
- count1();
- }
- static void count1(){
- int a=5;//利用位异或运算来实现,也是效率最高的一种
- int b=3;
- System.out.println("\n交换前:"+a+","+b);
- a=a^b;
- b=a^b;
- a=a^b;
- System.out.println("第三种交换方式");
- System.out.println("交换后:"+a+","+b);
- }
复制代码 |
|