交换2个变量的三种方式
1 /* 2 * 交换2个变量的三种方式: 3 * 1. 借助第三方变量 4 * 2. 不借助第三方变量,通过加减法 5 * 3. 通过异或运算 6 */ 7 8 public class ExchangeTwoVar { 9 10 public static void main(String[] args) { 11 exchangeByThirdVar(); 12 exchangeByPlusMinus(); 13 exchangeByXOR(); 14 15 } 16 17 // 1. 借助临时变量 18 public static void exchangeByThirdVar() { 19 int num1 = 10; 20 int num2 = 20; 21 22 int temp = num1; 23 num1 = num2; 24 num2 = temp; 25 26 System.out.println("num1 = " + num1 + " num2 = " + num2); 27 } 28 29 // 2. 通过加减法 30 public static void exchangeByPlusMinus() { 31 int num1 = 10; 32 int num2 = 20; 33 34 num1 = num1 + num2; 35 num2 = num1 - num2; 36 num1 = num1 - num2; 37 38 System.out.println("num1 = " + num1 + " num2 = " + num2); 39 } 40 41 // 3. 通过异或运算 ^ 42 public static void exchangeByXOR() { 43 int num1 = 10; 44 int num2 = 20; 45 46 num1 = num1 ^ num2; 47 num2 = num1 ^ num2; 48 num1 = num1 ^ num2; 49 50 System.out.println("num1 = " + num1 + " num2 = " + num2); 51 } 52 53 }
运行结果:
num1 = 20 num2 = 10 num1 = 20 num2 = 10 num1 = 20 num2 = 10
posted on 2019-05-21 20:52 _Stefanie 阅读(2421) 评论(0) 编辑 收藏 举报