Java Xor如何确定哪个int是不同的?
这是正在解决的问题 给您三个整数,a、b和c。保证其中两个整数相等。第三个整数的值是多少 这是密码Java Xor如何确定哪个int是不同的?,java,logical-operators,Java,Logical Operators,这是正在解决的问题 给您三个整数,a、b和c。保证其中两个整数相等。第三个整数的值是多少 这是密码 int extraNumber(int a, int b, int c) { return a^b^c; } 我理解插入符号“^”的意思是XOR,简单来说就是“这个或那个,但不是两个”,但我不理解的是,这段代码如何确定哪个int与其他int不同,或者我可能不正确理解XOR?从位级别看: 一个值xxor加上它本身总是会导致0(检查:1^1=0和0^0=0) 值y与0异或将始终产生相同的值
int extraNumber(int a, int b, int c) {
return a^b^c;
}
我理解插入符号“^”的意思是XOR,简单来说就是“这个或那个,但不是两个”,但我不理解的是,这段代码如何确定哪个int与其他int不同,或者我可能不正确理解XOR?从位级别看:
- 一个值
xor加上它本身总是会导致0(检查:x
和1^1=0
)0^0=0
- 值
与0异或将始终产生相同的值y
(检查:y
和1^0=1
)0^0=0
int
仅为32位,因此相同的规则适用于完整的int
值
因此,该方法不需要计算出“哪些值不同”,因为一个值本身与cancel out一起xor ed为0,而将“剩余”值与0进行xor运算只会返回相同的值。Joachim的答案是正确的,并且通过一个示例添加更多细节,假设您将三个参数(2、3、2)传递给方法,根据XOR的真值表,位级格式通常从右侧开始
您还可以通过将代码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)
X^X
是0
<代码>0^Y是Y
。因此X^X^Y
总是Y
。这同样适用于X^Y^X
和Y^X^X
。
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)