Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
时间: 2024-03-02 11:51:56 浏览: 27
To solve this problem, we can use bit manipulation. We can count the number of set bits at each position of all the integers in the array and then take the mod of this count by 3. This will give us the bit at that position in the single element.
Here's the code:
```
int singleNumber(vector<int>& nums) {
int result = 0;
for(int i=0; i<32; i++) {
int sum = 0;
for(int j=0; j<nums.size(); j++) {
if((nums[j]>>i) & 1) {
sum++;
}
}
result |= (sum % 3) << i;
}
return result;
}
```
In this code, we are iterating over all the 32 bits of an integer. For each bit position, we are counting the number of integers in the array that have a set bit at that position. We are then taking the mod of this count by 3 and setting the bit in the result integer accordingly. Finally, we are returning the result integer as the single element.