Xor 如何确定哪个 int 不同?

How does Xor determine which int is different?

这是正在解决的问题

"给你三个整数a,b,c,保证其中两个整数相等,第三个整数的值是多少?"

这是代码

int extraNumber(int a, int b, int c) {
    return a^b^c;
}

我理解插入符“^”的意思是 XOR,简单来说就是“这个或那个,但不是两者”,但我不明白的是这段代码如何确定哪个 int 与其他 int 不同,或者也许我没有正确理解 XOR?

比特级看:

  • x 与自身异或后的结果始终为 0(检查:1^1=00^0=0)。
  • 一个值 y 与 0 进行异或运算将始终得到相同的值 y(检查:1^0=10^0=0)。

因为它适用于单个位并且 int 只是 32 位,所以相同的规则适用于完整的 int 值。

因此,该方法不需要弄清楚“哪些值不同”,因为一个值与自身进行异或运算并取消为 0,并将“剩余”值与 0 进行异或运算只会 return相同的值。

Joachim 的回答是正确的,并通过示例添加更多细节,假设您将三个参数 (2, 3, 2) 传递给您的方法,位级格式通常 ...16 8 4 2 1 从右开始边,根据真相 table 异或,

https://en.wikipedia.org/wiki/XOR_gate

private int extraNumber(int a, int b, int c) {
        // 8421  -> this is bit level, 
        // let's compare a^b

        // 0010 = 2 (a value)
        // 0011 = 3 (b value, sum of 2nd + 1st bits)

        // 0001 = 1 (after XOR with a^b)
        // 0010 = 2 (c value)

        // 0011 = 3 (the final output)

        return a^b^c;
    }

您还可以通过将代码 a^b^c 分成两个语句来检查中间结果。

例如

int a = 0b1010_1010;
int b = 0b1010_1010; //same value as b

int c = 0b1111_0000; //the remaining item

//CASE 1 (xor the different values first)
int d = a^c; //  results in 0b0101_1010
int e = d^b; // results in 0b1111_0000 (the answer) 


//CASE 2 (xor the same values first)
int d = a^b; // results in 0b0000_0000
int e = d^c; // results in 0b1111_0000 (the answer)