XOR Operation Intuition

前端 未结 7 1614
滥情空心
滥情空心 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:42

    The Xor operator is commutative:

    1.      X ⊕ Y = Y ⊕ X                    for any integers X and Y
    

    and associative:

    2.      X ⊕ (Y ⊕ Z) = (X ⊕ Y) ⊕ Z      for any integers X, Y and Z
    

    It follows that the result of any sequence of xor operations is completely independent of the order of the operands (that is, the order of the elements in the array).

    3.     X ⊕ X = 0                         for any integer X
    
    4.     X ⊕ 0 = 0 ⊕ X = X                for any integer X
    

    In the problem we have an expression where each element Ai appears twice except some singular element B. the resulting Xor operation is equivalent to:

         (A1 ⊕ A1) ⊕ (A2 ⊕ A2) ⊕    ...   ⊕ B
     = 
             0      ⊕      0     ⊕    ...   ⊕ B
     = 
             B
    

    what sorts of keywords should I be paying attention to in order to figure out that I should be using an XOR operation for this question

    Some problems can be solved quickly using bit manipulation. After familiarizing with Boolean operators and their properties, and seeing enough applications like this one, you will naturally "feel" when they're useful to solve a given problem.

    0 讨论(0)
提交回复
热议问题