Explain using xor to find two non-duplicate integers in an array

后端 未结 4 1783
天涯浪人
天涯浪人 2020-12-23 12:23

Given [1,1,4,5,5,6] we can find 4 and 6 to be the non-repeating integers.

There is a solution using XOR.

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 12:56

    When you xor two equal values, they cancel out. This allows to reveal the non-repeating pair.

    XOR(aabbccddeeffgh) = XOR(gh) = ...1...
    

    Knowing any bit on which g and h differ allows to set g and h aside in two subsets:

    ...0... => XOR(aabbcceeg) = g
    
    ...1... => XOR(ddffh) = h
    

提交回复
热议问题