Share my C++ solution using XOR


  • 8
    V

    We can verify the associative law and the commutative law for XOR,and x^x = 0, x^0 = x

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int n = nums.size(), i = 0, ret = 0;
            
            for (i = 0; i < n; ++i)
                ret ^= nums[i];
                
            return ret;
        }
    };

Log in to reply
 

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