如何XOR变量交换工作? [英] How does XOR variable swapping work?
本文介绍了如何XOR变量交换工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可有人没有临时变量的作品给我解释一下两个变量如何XOR交换?
Can someone explain to me how XOR swapping of two variables with no temp variable works?
void xorSwap (int *x, int *y)
{
if (x != y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
据我了解它做什么,但可以有人走我走过它是如何工作的逻辑是什么?
I understand WHAT it does, but can someone walk me through the logic of how it works?
推荐答案
您可以看到它是如何工作做替代:
You can see how it works by doing the substitution:
x1 = x0 xor y0
y2 = x1 xor y0
x2 = x1 xor y2
替换,
x1 = x0 xor y0
y2 = (x0 xor y0) xor y0
x2 = (x0 xor y0) xor ((x0 xor y0) xor y0)
由于XOR是完全关联和交换:
Because xor is fully associative and commutative:
y2 = x0 xor (y0 xor y0)
x2 = (x0 xor x0) xor (y0 xor y0) xor y0
由于 X XOR点¯x== 0
对任意x
y2 = x0 xor 0
x2 = 0 xor 0 xor y0
和自 X XOR 0 == X
对任意x
y2 = x0
x2 = y0
和交换就完成了。
这篇关于如何XOR变量交换工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文