LeetCode刷题实战137:只出现一次的数字 II
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.
题意
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
解题
class Solution {
public:
int singleNumber(vector<int>& nums) {int res = 0;
for(int i = 0; i < 32; i++){
int sum = 0;
for(int num: nums)
if((num >> i) & 1)
sum++;
if(sum % 3)
res |= 1 << i;
}
return res;
}
};
评论