elegant one-line C# Linq Aggregate XOR


  • 0
    C

    beautiful and clear reads like a sentence

    although arguably ~20% slower than the best optimal XOR solution using single for loop

        public int MissingNumber(int[] nums) 
        {
            return Enumerable.Range(0, nums.Length + 1).Concat(nums).Aggregate((sum, k) => sum ^ k);
        }
    

  • 0
    C

    same thing C++

    class Solution 
    {
        int accumulate_xor(int n)
        {
            switch (n & 3)
            {
                case 0: return n;
                case 1: return 1;
                case 2: return (n + 1);
                case 3: return 0;
            }
        }
        
    public:
        int missingNumber(vector<int>& nums) 
        {
            return accumulate_xor(nums.size()) ^ std::accumulate(nums.begin(), nums.end(), 0, bit_xor<>());
        }
    
    };
    

Log in to reply
 

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