交換兩個數值的四種方法

方法一:

這種交換方法是最經常使用的一種方式,即引入第三個變量充當交換介質.java

class SwapTwoNums{
	public static void main(String[] args){
		int a = 3;
		int b = 4;
		System.out.println("Numbers before swap: " + "a = " + a +", b = " + b);
		
		int temp = a;
		a = b;
		b = temp;
		System.out.println("Numbers after swap: " + "a = " + a +", b = " + b);
	}
}

方法二

直接賦值,先計算兩者之和,而後把a的值賦給b,最後兩者之和再減去a的值獲得b,最後賦給a.code

class SwapTwoNums{
	public static void main(String[] args){
		int a = 3;
		int b = 4;
		System.out.println("Numbers before swap: " + "a = " + a +", b = " + b);
		
        a = (a + b) - (b = a);
		System.out.println("Numbers after swap: " + "a = " + a +", b = " + b);
	}
}

方法三

另外一種直接賦值方式,實質同方法二.class

class SwapTwoNums{
	public static void main(String[] args){
		int a = 3;
		int b = 4;
		System.out.println("Numbers before swap: " + "a = " + a +", b = " + b);
		
        a = a + b;
		b = a - b;
		a = a - b;
		System.out.println("Numbers after swap: " + "a = " + a +", b = " + b);
	}
}

方法四

利用一個數同另外一個數做兩次異或運算,結果等於自己.即a = a ^ b ^ b.變量

class SwapTwoNums{
	public static void main(String[] args){
		int a = 3;
		int b = 4;
		System.out.println("Numbers before swap: " + "a = " + a +", b = " + b);
		
        a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println("Numbers after swap: " + "a = " + a +", b = " + b);
	}
}

備註:方法二和三存在上溢的可能,即假若a和b數值均很是大,兩者之和可能會超出該類型數所能表達的最大範圍.而方法四相對來講不會有這種問題.方法

相關文章
相關標籤/搜索