简体   繁体   中英

Signed Integer Overflow[C++]

Objective Find minimum value in stack in O(1) time complexity.

Issue : Failing at the below operation (2*x-minEle) in some Leetcode testcases.

Actual Error - runtime error: signed integer overflow: 2 * -2147483648 cannot be represented in type 'int'

I tried replacing every integer value with long long datatype but still getting the same error

Following is the code :

class MinStack {
public:
    int minEle = INT_MAX;
    vector<int> s;
    void push(int x) {
        if(s.empty())
        {
            minEle=x;
            s.push_back(x);
            return;
        }
        if(x<minEle)
        {
            s.push_back(2*x-minEle);
            minEle = x;
        }
        else
            s.push_back(x);    
    }
    
    void pop() {
        int y = s.back();
        if(y<minEle)
        {
            minEle = 2*minEle - y;
        }
        s.pop_back();
    }
    
    int top() {
        return s.back();
    }
    
    int getMin() {
        return minEle;
    }
};

I also face the same problem on a programming challenge site but didn't encounter an "integer overflow" on IDE. "long long" data type works for me on IDE.

As per my understanding, your x is int when you multiply INT_MIN * 2 it goes out of the range of int. as int * int results in int. so changing data type of x to long long int might solve the issue. Just look at the code I am posting below with some modification.

class MinStack {
    stack<long long int> s;
    long long int mini;
public:
    MinStack() {
        mini = INT_MAX;
    }
    
    void push(int val) {
        long long nval = val;
        if (s.empty()) {
            mini = nval;
            s.push(nval);
            return;
        }
        else if (nval < mini) {
            s.push(2 * nval - mini);
            mini = nval;
        }

        else
            s.push(nval);
    }
    

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM