题目:
Given an array of integers, every element appears three times
except for one. Find that single one.
思路:
那么对这32位中的每一位做相同的处理,也就是说,逐位把所有的输入加起来,并且看看第i位的和除以3的余数,这个余数就是single numer在第i位的取值。这样就得到了single number在第i位的取值。
程序:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int count[32]={0};
int result=0;
int n = nums.size();
for(int i=0;i<32;i++){
for(int j=0;j<n;j++){
count[i]+=((nums[j]>>i)&1);
count[i]=count[i]%3;
}
result|=(count[i]<<i);
}
return result;
}
};