怎樣用Java實現兩個數的交換?
package com.echo;public class SwapTwoNumbers { public static void main(String[] args) { int a = 10;
int b = 20;
1)用第三方變量(開發用)
int temp = a;
a = b;
b = temp;
System.out.println("1)用第三方變量實現:" + "a = " + a + ",b = " + b);
// 2)用變量相加實現
// a = a + b;
// b = a - b;
// a = a - b;
// System.out.println("2)用變量相加實現:" + "a = " + a + ",b = " + b);
// 3)用位異或實現(面試用)
// ^特點:一個數據對另一個數據異或兩次,該數本身不變
// 左邊:a b a
// 右邊:a^b
// a = a ^ b;
// b = a ^ b; // a ^ b ^ b = a
// a = a ^ b; // a ^ a ^ b = b
// System.out.println("3)用位異或實現:" + "a = " + a + ",b = " + b);
// 4)一句話搞定
b = (a + b) - (a = b); // b = 10, a = 20
System.out.println("4)一句話實現:" + "a = " + a + ",b = " + b);
}}