Example: Missing Number - rFronteddu/general_wiki GitHub Wiki

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

class Solution {
    public int missingNumber(int[] nums) {
        int ans = 0;
        // XOR is associative and commutative, 
        // the XOR of all numbers from 0 to n will cancel out with the XOR of 
        // all array elements except for the missing number.
        for (int i = 0; i <= nums.length; i++) {
            ans = ans ^ i;
        }

        for (int i = 0; i < nums.length; i++) {
            // the xor will cancel out except with the missing number!
            ans = ans ^ nums[i];
        }
        return ans;
    }