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?
解法一:
用一个INT数字,记录每个bit上1出现的次数。然后求次数对3的余数,就是出现一次的数字在bit上的值。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(int i=0;i<32; i++){
int sum = 0;
for(int j=0; j<nums.size(); j++){
sum += (nums[j]>>i) & 1;
}
res |= (sum%3)<<i;
}
return res;
}
};