1. 程式人生 > >不借助第三者實現兩個變數的交換(java&&C)

不借助第三者實現兩個變數的交換(java&&C)

1.原理:a^b^b = a

2.實現

java:

package javaPractice;

import java.util.*;

public class Exchange {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
	
		a = a^b;
		b = a^b;
		a = a^b;
		
		System.out.println("交換後的值為a和b分別為"+a+","+b);
	}
}

 

C語言:

#include<stdio.h>
#include<stdlib.h>
int main() 
{
	int a,b;
	printf("input a ,b:\n");
	scanf_s("%d%d",&a,&b);
	a = a^b;
	b = b^a;
	a = a^b;
	printf("after swaping \na:%d\nb:%d\n",a,b);
	system("pause");
	return 0;
}