For bit i, sum ((x >> i) & 1) over all x; if the sum mod 3 is 1, set bit i in the answer.
Approach 1
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < 32; i++) {
int count = 0;
for (int x : nums) count += (x >> i) & 1;
if (count % 3 != 0) result |= 1 << i;
}
return result;
}
}
Verdict: Generalises to "appears k times".
2
Two-register state machine
Time O(n) Space O(1)
ones and twos hold bits seen once and twice (mod 3): ones = (ones ^ x) & ~twos; twos = (twos ^ x) & ~ones.
Approach 2
class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for (int x : nums) {
ones = (ones ^ x) & ~twos;
twos = (twos ^ x) & ~ones;
}
return ones;
}
}