Simple C++ codes


  • 20
    D

    Using bit XOR operatons, just like the "find missing number (all elements except one occur twice, find the one that occurs once)" one
    The reason I didn't use sum[1..n] - sum(nums) is that calculating sum has potential to cause overflow. XOR bit operation is much safer.

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int missing =0;
            for(int i=0; i<nums.size();++i) 
                missing ^= ((i+1)^nums[i]);
            return missing;
        }
    };

  • 0

    Easy to understand, and as usual, I have learned a lot. a^b^c^d^e^a^b^c^d^e=0; a^b^c^a^b=c. Thank you.


  • 0

    By the way, are there other tricks about "| ^ &"?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.