Sword Finger Offer 56-II. Number of occurrences of numbers in the array II

Except for a number that appears only once in an array nums, all other numbers appear three times. Please find the number that appears only once.

Example 1:

Input: nums = [3,4,3,3]
Output: 4

Example 2:

Input: nums = [9,1,7,9,7,9,7]
Output: 1

limit:

1 <= nums.length <= 10000
1 <= nums[i] < 2^31

Caiji really doesn't know how to automate, so I can only use a little bit of rubbish.

class Solution {
    
    
public:
    int singleNumber(vector<int>& nums) {
    
    
        int ma[32];
        memset(ma,0,sizeof(ma));
        for(int i=0;i<nums.size();i++)
        {
    
    
            int j=0;
            while(nums[i])
            {
    
    
                if(nums[i]&1)
                {
    
    
                    ma[j]++;
                }
                j++;
                nums[i]>>=1;
            }
        }




        long ans=0;
        long cnt=1;
        for(int i=0;i<32;i++)
        {
    
    
            if(ma[i]%3==1)
            {
    
    
                ans+=cnt;
            }

            cnt<<=1;
        }


        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_43624038/article/details/113780690