[Problem]
[Solution]
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?
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// invalid
if(n <= 0)return 0;
int ones = 0, twos = 0, mask = 0;
for(int i = 0; i < n; ++i){
twos |= (ones & A[i]);
ones ^= A[i];
mask = ~(ones & twos);
ones &= mask;
twos &= mask;
}
// the one could occurs one time or two times, but no more than three times
return ones == 0 ? twos : ones;
}
};