Problems:
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?
解法一:按位统计0、1出现的次数。使用每个数的每位相加,取模运算,来获得结果。
class Solution {
public:
int singleNumber(vector<int>& nums) {
const int N=sizeof(int)*8;
int count[N];
fill_n(&count[0],N,0);
for(int i=0;i<nums.size();i++)
for(int j=0;j<N;j++)
{
count[j]+=(nums[i]>>j)&1;
count[j]%=3;
}
//返回结果
int result=0;
for(int j=0;j<N;j++)
result+=(count[j]<<j);
return result;
}
};
The second solution is need update.