Skip to content

Magical xor operator #26

@phucledien

Description

@phucledien

XOR ^ or (exclusive or operator), the first time I saw this operator is at the Introduction to Digital Circuits class.

At the first time, I think ok, so this operator will have these properties

n ^ n = 0
n ^ 0 = n

And I don't think much about this or it's use-case

But after seeing how this operator is used to solve the problem: find the number which is not repeated. It really blows my mind 🤯

Input: [4,1,2,1,2]
Output: 4
func singleNumber(_ nums: [Int]) -> Int {
  var result = 0
  for num in nums {
    result ^= num    
  }
  return result
}

Run step

1. num = 4 (0100)
result = 0100 ^ 0000 = 0100

2. num = 1 (0001)
result = 0100 ^ 0001 = 0101

3. num = 2 (0010)
result = 0101 ^ 0010 = 0111

4. num = 1
result = 0111 ^ 0001 = 0110

5. num = 2
result = 0110 ^ 0010 = 0100 (4) 

ref: https://hackernoon.com/xor-the-magical-bit-wise-operator-24d3012ed821

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions