Java Math 4 lines solution


  • 0
    H

    Just calculating all the nums and subtract by the sum it should be.

    public int missingNumber(int[] nums) {
            int sum = 0;
            for(int i:nums){
                sum += i;
            }
            return nums.length*(nums.length+1)/2 - sum;
            
            
        }
    

  • 1
    I

    why the sum it should be is "nums.length * (nums.length + 1) / 2"


  • 0
    H

    from 0,1,2...n the sum calculate formula is (0+n)(n+1)/2 and subtract the given nums , we can get the target missing number
    for example:
    we have 0 1 3 , suppose we should have 0 1 2 3 the sum should be 3
    4/2 = 6,but the given sum is 4, so the missing number is 2.
    I hope you can understand that :)


  • 1
    I

    Thanks for your reply. Totally understood your clear code.


Log in to reply
 

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