交换两个变量值的四种方法

 


public class swopDemo {

	public static void main(String[] args) {
		
		int a=20, b=30;
		
		//方式一:使用第三方变量(开发)
		int c = a;
		a = b;
		b = c;
		System.out.println("a=" + a + ", b=" + b);
		
		//方式二:用位异或方式(面试)
		a = a ^ b;  
		b = a ^ b;  //a ^ b ^ b = a
		a = a ^ b;  //a ^ b ^ a = b
		System.out.println("a=" + a + ", b=" + b);
		
		//方式三:变量相加
		a = a + b;  //a = 30 + 20 = 50
		b = a - b;  //b = 50 - 30 = 20
		a = a - b;  //a = 50 - 20 = 30
		System.out.println("a=" + a + ", b=" + b);
		
		//方式四:一站式服务
		b = (a+b) - (a=b); // b = 50 - 20 = 30    a = 20
		System.out.println("a=" + a + ", b=" + b);
	}

}
#include 

int main(){
	
	int a=30, b=20;
	 
	//方式一:使用第三方变量(开发) 
	int c = a;
	a = b;
	b = c;
	printf("a=%d, b=%d \n", a, b); 
	
	//方式二:用位异或方式(面试)
	a = a ^ b;  
	b = a ^ b;  //a ^ b ^ b = a
	a = a ^ b;  //a ^ b ^ a = b
	printf("a=%d, b=%d \n", a, b);
	
	//方式三:变量相加
	a = a + b;  //a = 30 + 20 = 50
	b = a - b;  //b = 50 - 30 = 20
	a = a - b;  //a = 50 - 20 = 30
	printf("a=%d, b=%d \n", a, b);
		
	//方式四:一站式服务
	b = (a+b) - (a=b); // b = 50 - 20 = 30    a = 20
	printf("a=%d, b=%d \n", a, b);
	
	return 0;
} 

 

你可能感兴趣的:(数据结构-算法)