题目要求:
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?
对于n个整数,统计每位上出现1的次数;若能被3整除,说明要求的数在这一位为0,否则为1,从而得到要求的数。
代码实现:
class Solution {
public:
int singleNumber(int A[], int n) {
int bits[sizeof(int)*8] = {0};
int result = 0;
for(int i = 0; i < sizeof(int)*8; i++)
for(int j = 0; j <n; j++)
bits[i] +=((A[j] >> i) & 1);
for(int i = 0; i < sizeof(int)*8; i++)
if(bits[i] % 3)
result += (1 << i);
return result;
}
};