Leetcode 137. Digital II appears only once and problem-solving ideas implemented in C ++

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/gjh13/article/details/90728971

Problem-solving ideas:

Number 32 were statistically 1 tmp, tmp then performed on modulo 3, will be able to remove the occurrence frequency of three times. Finally, these results are applied to the res bit by tmp << i.

 

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for(int i = 0; i < 32; i++){
            int tmp = 0;
            for(int j = 0; j < nums.size(); j++)
                tmp += nums[j] >> i & 1;
            tmp = tmp % 3;
            res += tmp << i;
        }
        return res;
    }
};

 

This question is a better approach is the method state machine, detailed look at the blog: https://blog.csdn.net/koala_tree/article/details/80228525

Guess you like

Origin blog.csdn.net/gjh13/article/details/90728971