My clear cpp code using xor


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

Log in to reply
 

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