Java中"与"、"或"、"非"、"异或"

2,205 阅读2分钟

&  按位"与"操作符

public class Demo {
    public static void main(String[] args) {

        // &操作符
        int a = 16;
        //16转换为二进制为10000
        int b = 17;
        //17转换为二进制为10001

        // 两个操作数都为1时才为1

        //    10000
        // &  10001
        //--------------
        //    10000

        System.out.println(a&b);

        //输出为16
    }
}

| 按位"或"操作符

public class Demo {
    public static void main(String[] args) {

        // |操作符        int a = 16;
        //16转换为二进制为10000
        int b = 17;
        //17转换为二进制为10001

        // 两个操作数只要有一个1就为1

        //    10000
        // |  10001
        //--------------
        //    10001

        System.out.println(a|b);

        //输出为17
    }
}

~ "取反"操作符

public class Demo {
    public static void main(String[] args) {

        // ~操作符
        int a = 8;
        //8转换为二进制为1000
        // 补符号位为
        // 01000
        // 进行取反运算为
        // 10111 (补码)
        // 转源码除符号位取反+1
        // 11001
        System.out.println(~a);

        //输出为-9
    }
}

^ "异或"操作符

public class Demo {
    public static void main(String[] args) {

        // ^操作符
        int a = 8;
        int b = 9;
        //8转换为二进制为1000
        //9转换为二进制为1001
        // 异或规则相同为0不同为1
        //    1000
        // |  1001
        //--------------
        //    0001
        System.out.println(a^b);

        //输出为1
    }
}

假如有一个数组中有两个相同的内容只有一个是不一样的,那么如何找到这个不一样的数。

可能我叙述的不太容易理解,假如我们有以下数组。

int temp = {1,2,3,4,5,4,3,2,1};

可以看到数组中的1、2、3、4都是有两个,但是只有5有一个,而我们要做的就是找到这个5。

如何用十分简洁的代码就可以实现这个功能呢?

这里使用了一个异或的特性。

public class Demo {
    public static void main(String[] args) {

        int[] temp = {1,2,5,2,1,4,4,15,5};
        int a = 0;
        for(int i=0;i<temp.length;i++) {
            a = a ^ temp[i];
        }
        System.out.println(a);
    }
}

运行这段代码。

C:\Users\PiLiPaLa\Desktop\Code\Eight>java Demo
15

成功的将15输出了。

其实原理就是异或,有两个相同的数就会抵消变成0,然后只剩下单独的那一个。