题目要求:
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?
class Solution {
public:
int singleNumber(int A[], int n) {
int res = 0;
for (size_t i =0; i < 32; ++i) {
int d = 1 << i;
int cnt = 0;
for (size_t j = 0; j < n; ++j) {//统计第i位是1的个数, 如果出现统计结果不能被3整除,那么single number 这位上肯定是1
if(A[j] & d)
cnt++;
}
if((cnt % 3) != 0)
res |= d;
}
return res;
}
};