Don't you think the SUM method will cause the integer overflow if it is tested with extremely large numbers?


  • 0
    D

    Don't you think the SUM method will cause the integer overflow if it is tested with extremely large numbers?


  • 3
    S

    We can avoid that using the code below. The idea is similar to using sum.

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int res = nums.size();
            for (int i = 0; i < nums.size(); ++i){
                res += i;
                res -= nums[i];
            }
            return res;
        }
    };
    

    actually we can replace the + and - signs with ^ and it'll still work (bit manipulation).

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

  • 0
    D

    The first method does make sense. Thank you!


  • 0
    S

    happy coding :)


  • 0
    V

    The first solution seems unreliable: [INT_MAX, INT_MAX - 1, ...] will make it underflow.


Log in to reply
 

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