- /*
- * 需求:用尽可能多的方法实现两个整数的互换
- */
- public class ExchangeTest {
- public static void main(String[] args) {
- int a = 10;
- int b = 20;
- //方式1 引入第三方变量(开发中用)
- int temp = a;
- a = b;
- b = temp;
-
- System.out.println("a:"+a+",b:"+b);
- System.out.println("-----------------");
-
- //方式2 a+b和的方式
- a = a + b; //30
- b = a - b; //30 - 20 = 10
- a = a - b; //30 - 10 = 20
-
- System.out.println("a:"+a+",b:"+b);
- System.out.println("-----------------");
-
- //方式3 异或的方式
- a = a ^ b;
- b = a ^ b; //a^b^b = a
- a = a ^ b; //a^b^a = b
- System.out.println("a:"+a+",b:"+b);
- System.out.println("-----------------");
-
- //方式4 一句话搞定加减法
- b = (a + b) - (a = b);
-
- System.out.println("a:"+a+",b:"+b);
- System.out.println("-----------------");
-
- //方式5 一句话搞定乘除法
- b = (a*b)/(a=b);
-
- System.out.println("a:"+a+",b:"+b);
- System.out.println("-----------------");
-
- }
- }
复制代码 |
|