leetcode 1541 数组中数字出现的次数 II

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

对于每一个二进制位,计算出现几次(count表示),若count%3==1,那么则该位必然有我们需要求的那个数字,直接加上。

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         int ans=0;
 5         for(int i=0;i<32;i++)
 6         {
 7             int count=0;
 8             for(auto x:nums)
 9             {
10                 if(x&(1<<i))
11                   count++;
12             }
13             if(count%3)
14             ans+=1<<i;
15         }
16         return ans;
17     }
18 };
原文地址:https://www.cnblogs.com/Carits/p/12424713.html