程式語言 - LeetCode - C++ - 136. Single Number



參考資訊:
https://algo.monster/liteproblems/136

題目:


解答一:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int r = 0;

        for (int n : nums) {
            r ^= n;
        }
        return r;
    }
};

解答二:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;

        for (int i = 0; i < 32; ++i) {
            int cnt = 0;

            for (int n : nums) {
                cnt += !!(n & (1 << i));
            }

            if (cnt % 2) {
                ans |= (1 << i);
            }
        }

        return ans;
    }
};