变量交换是编程中经常使用的功能,本文记录几种不通过不添加第三方变量来交换两个变量的实现方式。

交换变量通常采用类似如下代码:

int a = 3, b = 4, temp;
temp = a;
a = b;
b = temp;
System.out.println(a);
System.out.println(b);

上述代码实现和理解起来都很容易,除此之外还有其它的实现方式,本文以非0的int变量为例,简单记录下自己了解的相关实现。

加减法实现

int a = 3, b = 4;
a = a + b;
b = a - b;
a = a - b;
System.out.println(a);
System.out.println(b);

上述代码可以进一步精简如下:

int a = 3, b = 4;
a = a + b - (b = a);
System.out.println(a);
System.out.println(b);

乘除法实现

int a = 3, b = 4;
a = a * b;
b = a / b;
a = a / b;
System.out.println(a);
System.out.println(b);

位运算实现

int a = 3, b = 4;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a);
System.out.println(b);