Timeline
timeline
2025-11-25
init
bit manipulation
Problem:
For XOR, if number x appears multiple times:
x ^ x = 0
x ^ x ^ x = x
x ^ x ^ x ^ x = 0
…
So: even count ⇒ cancels to 0, odd count ⇒ leaves 1 x
Can be understood from a deeper perspective:XOR is a ‘mod 2 addition without carry’
For example:
- 1 ^ 1 = (1 + 1) mod 2 = 0
- 1 ^ 1 ^ 1 = (1 + 1 + 1) mod 2 = 1
Fully consistent: - Even times → mod 2 = 0
- Odd number of times → mod 2 = x
And the other numbers in the problem appear three times, we need to take modulo 3:
- For each bit (0/1), among three identical numbers, this bit appears three times:
- If this bit is 0: 0+0+0 = 0 (mod 3)
- If this bit is 1: 1+1+1 = 3 ≡ 0 (mod 3)
This whole process is equivalent to:Adding each bit and performing modulo 3 operation。
1 |
|
