简体   繁体   中英

getting an error of signed integer overflow(c++)

please help me in resolving the error in below code:

int smallestRangeII(vector<int>& A, int k) {
        sort(A.begin(), A.end());
        int mini = INT_MAX;
        int maxi = INT_MIN;
        int x, y;
        int n = A.size();
        for(int i=0;i<n;i++){
            x = A[i]+k;
            y = A[i]-k;
            if(x <= A[n-1] && x<=maxi)
                maxi = x;
            else if(y>=A[0] && y>=mini)
                mini = y;
        }
        return (maxi - mini);
    }

I am getting an error of

runtime error: signed integer overflow: -2147483648 - 2147483647 cannot be represented in type 'int' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:27:22

Thanks in advance

You are returning a signed integer where the value is the difference between the maximum and minimum integer values (that is possible for empty A ). Even if A is not empty, there is no guarantee that A doesn't contain these extreme values. The value INT_MAX - INT_MIN is twice as large as the value the int type can represent.

One possible solution is to return an unsigned int :

unsigned int smallestRangeII(vector<int>& A, int k);

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