Java solution by add,xor


  • 0
    R

    If the number not miss,array{0,1,...,n} sum to be X(0+1+...+n).
    The sum(missing array) plus the missing number is equal to X(0+1+...+n).
    So, missing number=X(0+1+...+n)-sum(missing array).

            int l = 0, k = nums.length;
            for (int i = 0; i < nums.length; i++) {
                //k:the sum of not miss array
                k = k + i;
                //l:the sum of miss array
                l = l + nums[i];
            }
            return k - l;
    

    Transfer to xor:

            int k = nums.length;
            for (int i = 0; i < nums.length; i++) {
                k = k ^ i ^ nums[i];
            }
            return k;
    

    My English is not very good,express may not accurate, please forgive me.


Log in to reply
 

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