class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int size = nums.size();
        int ans = 0;
        for(int i = 0;i < 32;i++)
        {
            int sum = 0;
            for(auto num:nums)
            {
                sum += ((num >> i)&1);
            }

            if(sum % 3)
                ans |= (1 << i);
        }
        return ans;
    }
};

运行效率:

Runtime: 4 ms, faster than 98.04% of C++ online submissions for Single Number II.
Memory Usage: 9.6 MB, less than 51.01% of C++ online submissions for Single Number II.

比较奇怪的是下面的写法确报错:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int size = nums.size();
        int ans = 0;
        for(int i = 0;i < 32;i++)
        {
            int sum = 0;
            for(int i = 0;i < nums.size();i++)
            {
                sum += ((nums[i] >> i)&1);
            }

            if(sum % 3)
                ans |= (1 << i);
        }
        return ans;
    }
};

输出结果是-1,原因还需要探讨一下子。