why long long key = 2147483647 + 2147483647; key = -2 ?


  • 0
    M

    My code:
    class Solution {
    public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
    int num = nums.size();
    int n = 0, m =0;
    long long key;
    for(; n < num; n++)
    {
    m = n;
    for(; m < num-1; m++)
    {
    key = nums[n] - nums[m+1];
    if(key > 2147483647 || key <= -2147483648)
    return false;
    if(abs(nums[n] - nums[m+1]) <= t)
    if(abs(n-m-1) <= k)
    return true;

            }
        }
        return false;
    }
    

    };


  • 0
    N

    when you compute 2147483647 + 2147483647, both of them are of int type. At first, the sum is also of int type, so you get -2. Then int type is cast into long long type, still -2. You can solve this by long long key = (long long)2147483647 + 2147483647.


Log in to reply
 

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