My c++ solution using bit manipulation.

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

    The main idea is similar to the problem Single Number,
    we can xor all the numbers in the array and the numbers from 0 to n together,
    the missing number will occur only once, so the result is the missing number.

Log in to reply

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