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?
此题的方法可以解释如下:用一个长度为32为的数组存储给定数组的对应位置的1的出现的总的次数,然后模3得到出现次数不为3的数,可以扩展到任意n>3均成立
class Solution {
public:
int singleNumber(int A[], int n) {
int sum[32]={0};
int res=0;
for(int i=0;i<32;i++)
{
for(int j=0;j<n;j++)
{
sum[i]+=(A[j]>>i)&1;
}
res|=(sum[i]%3)<<i;
}
return res;
}
};