Cover image for Top 150 Interview Questions P137 Single Number II

Top 150 Interview Questions P137 Single Number II


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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using std::vector;

class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
int total = 0;
for (int i = 0; i < 32; ++i) {
total = 0;
for (int num: nums)
total += ((num >> i) & 0x1);

if (total % 3)
ans |= (0x1 << i);

}
return ans;
}
};