import org.junit.Test; /* * 实现两个整数交换的4种方法 */ public class NumberChange { //1.采用第三方变量 @Test public void test1(){ int i = 10; int j = 20; System.out.println("i=" + i + ",j=" + j); //数值交换 int k = i; i = j; j = k; System.out.println("i =" + i + ",j=" + j); System.out.println("------------------"); } @Test public void test2(){ //2.异或位运算 ^ int i = 10; int j = 20; System.out.println("i=" + i + ",j=" + j); i = i ^ j; j = i ^ j;//j = i ^ j ^ j i = i ^ j;//i = i ^ j ^ i System.out.println("i=" + i + ",j=" + j); System.out.println("------------------"); } //3.加法 @Test public void test3(){ int i = 10; int j = 20; System.out.println("i=" + i + ",j=" + j); i = i + j; j = i - j; i = i - j; System.out.println("i=" + i + ",j=" + j); System.out.println("------------------"); } //4.一句话搞定 @Test public void test4(){ int i = 10; int j = 20; System.out.println("i=" + i + ",j=" + j); j = (i + j) - (i = j); System.out.println("i=" + i + ",j=" + j); } } |