LeetCode: Single Number II

LeetCode: Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

1
2
3
4
5
6
7
8
9
10
11
12
13
public class SingleNumberII {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0, threes = 0;
for (int num : nums) {
twos |= ones & num;
ones ^= num;
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
}
}

The truth is that I cannot understand this logic easily. I used those two links for details.