总结无需中间变量交换两个变量的值的方法

版权声明:博主GitHub网址https://github.com/29DCH,欢迎大家前来交流探讨和fork。 https://blog.csdn.net/CowBoySoBusy/article/details/82048566

依靠中间变量交换两个变量的值的方法想必大家已十分熟悉,这也是在程序设计和解决工程问题的时候经常使用的方法.

但是有些时候根据一些特定的性质,我们不需要借助第三方变量来交换指定两个变量的值.

class SwapTest {
	public static void main(String[] args) {
		/*
		* 位异或运算符的特点
		* ^的特点:一个数据对另一个数据位异或两次,该数本身不变。
		*/
		int x = 10;
		int y = 5;
		//需要第三方变量,开发推荐用这种
		/*
        int temp;
		temp = x;
		x = y;
		y = temp;
        */
		//不需要定义第三方变量,有弊端,有可能会超出int的取值范围
		/*
        x = x + y;				
		y = x - y;				
		x = x - y; 
        */
		//不需要第三方变量,通过^来做
		x = x ^ y;				
		y = x ^ y;				
		x = x ^ y;
		System.out.println("x = " + x + ",y = " + y);
	}
}

猜你喜欢

转载自blog.csdn.net/CowBoySoBusy/article/details/82048566