异或原理:
转换两个字符或数为2进制的ASCII码,再按位异或,即
0001 0001 ---> 0000
0000 0000 ---> 0000
0001 0000 ---> 0001
0000 0001 ---> 0001
异或交换位置例子
import java.util.Scanner; public class xor { //异或,英文为exclusive OR,或缩写成xor
public static void main (String[] args){ System.out.println("请输入x(enter) y(enter)"); Scanner in = new Scanner(System.in); int x = in.nextInt(); int y = in.nextInt(); x = x^y; y = y^x; x = x^y; System.out.println("x=" +x); System.out.println("y=" +y); } }
例如输入5(0101) 9(1001)时,
x = 0101; y = 1001;
x = x^y = 1100;
y = y^x = 1001^1100 = 0101;
x = x^y = 0101^1100 = 1001;