package cn.sxy.demo;
import java.util.Scanner;
/**
* 通过异或运算,实现两个变量的交换
*/
public class Demo18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入第一个变量");
int first = sc.nextInt();
System.out.println("输入第二个变量");
int second = sc.nextInt();
System.out.println("first=" + first + "\n" + "second=" + second);
System.out.println("将变量进行交换");
first = first ^ second; //first = 3
second = second ^ first; //second =
first = first ^ second;
System.out.println("first=" + first + "\n" + "second=" + second);
}
/**
* 例子:first = 1 ; second = 2
*
* first = 1 --> 0001
* second = 2 --> 0010
* first = first ^ second ==> 0001
* 0010
* --------
* first 0011 --->3
*
* first = 3 -->0011
* second = 2 -->0010
* second = second ^ first ==>0010
* 0011
* -------
* second 0001 --->1
*
* first = first ^ second ==>0011
* 0001
* -------
* first 0010 --->2
* ===> first = 2 ; second = 1
*/
}