XOR Operation Intuition

前端 未结 7 1615
滥情空心
滥情空心 2020-12-24 07:12

I recently came across this question on Leetcode and figured out a solution that I need some clarification with:

Given an array of integers, every ele

7条回答
  •  一生所求
    2020-12-24 07:32

    As I am sure you are familiar with, integers are stored in memory as tuples of binary digits. One can view each digit as a number in the field of two elements, which is essentially integers modulo 2. The ^ operator is component-wise xor, and with this interpretation, xor is simply addition. That is, we are adding the binary digits with each other.

    In this field, 1 + 1 = 0, so one can say that two is zero. Since addition is commutative and associative we can combine all the numbers at once. Anything that is added an even number of times will add nothing, and only the number that is added a single time ends up in the result variable.

    It might be interesting to know that the boolean operations are represented this way as (try it!): a xor b = a + b, a and b = ab, a or b = ab + a + b, not a = a + 1.

提交回复
热议问题