Avoid int overflow while using sum to get solution!!


  • 0
    H

    I saw top voted solutions don't consider int overflow when using sum to tell missing number, here is my solution:

    public class Solution {
        public int missingNumber(int[] nums) {
            int n = nums.length, basic = 0, sum = 0;
            //sum formula is n*(n+1)/2, if n is even, add n/2 for n+1 times, otherwise add (n+1)/2 for n times;
            if ((n & 1) == 0) basic = n / 2;         
            else basic = (n + 1) / 2;
            for(int i = 0;i < n;++i) {
                sum = sum + basic - nums[i];
            }
            if((n & 1) == 0) sum += basic;
            return sum;
        }
    }
    

Log in to reply
 

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