java异或运算

java异或运算符"^",将两个数转成二进制后,从高位到地位依次进行异或运算:相同得0,不同得1,最后再将异或运算的结果转为十进制数。

1.例子
3 ^ 10 = 9。
3==>0011,
10==>1010,
0011^1010=1001,
1001==>9。

2.取数对例子

public static void main(String[] args) {
    //找出相同的数对
    int N = 1001;
    int[] arr = new int[N];
    //赋值前N-1
    for (int i = 0; i < arr.length-1; i++) {
        arr[i] = i + 1;
    }
    //最末一位
    arr[N-1] = new Random().nextInt(N-1) + 1;

    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + "\t");
    }
    //随机下标
    int dex = new Random().nextInt(N);
    //交换
    int temp = arr[dex];
    arr[dex] = arr[N-1];
    arr[N-1] = temp;
    System.out.println("\n" + "------");
    //
    int x1 = 0;
    for (int i = 1; i <= N-1; i++) {
        x1 = x1 ^ i;
    }
    System.out.println("下标异或:" + x1);
    for (int i = 0; i < N; i++) {
        x1 = x1 ^ arr[i];
    }
    System.out.println(x1);

    //额外空间
    int[] helper = new int[N];
    for (int i = 0; i < N; i++) {
        helper[arr[i]] ++;
    }
    for (int i = 0; i < N; i++) {
        if (helper[i] == 2){
            System.out.println(i);
            break;
        }
    }
}