Search code examples
c++runtime-error

runtime error: signed integer overflow: 2147453785 + 36049 cannot be represented in type 'int'


I get the following error on running the code below: I am trying to solve a LeetCode problem and I get this error. I changed the datatype from int to long long int but I still get it. Can someone please help me ?

Line 130: Char 39: runtime error: signed integer overflow: 2147453785 + 36049 cannot be represented in type 'int' (stl_numeric.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_numeric.h:139:39

The code I have written is:

class Solution {
public:
    int minimumAverageDifference(vector<int>& nums) {
        long long int n = nums.size();
        long long int sumfromstart = 0;
        long long int sumfromend = accumulate(nums.begin(),nums.end(),0);
        int res = INT_MAX;
        int index = 0;
        for(int i=0; i<n; i++)
        {
            sumfromstart += nums[i];
            sumfromend -= nums[i];
            int a = sumfromstart/(i+1);
            int b = (i == n-1) ? 0 : sumfromend/(n-i-1);
            int avg = abs(a-b);
            if(avg < res)
            {
                res = avg;
                index = i;
            }
        }
        return index;
    }
};

Solution

  • std::accumulate is a templated function that in this case is defined as follows (prior to C++20):

    template< class InputIt, class T >
    T accumulate( InputIt first, InputIt last, T init );
    

    Since accumulate returns a value of type T, and the type of the third parameter (T init) is of type T, whatever type you pass as the third parameter will be used to accumulate the result value. In your case, that's type int, because:

            //                                This is a literal of type `int`
            //                                                            ▼
            long long int sumfromend = accumulate(nums.begin(),nums.end(),0);
            //                       ▲
            //  Implicit cast from `int` to `long long int`
    

    You can fix this by using a literal of type long long (that's the short-form for long long int) instead, which is defined by appending 2 l or L characters to the end of a number literal, like this:

            //                            This is a literal of type `long long`
            //                                                            ▼▼▼
            long long int sumfromend = accumulate(nums.begin(),nums.end(),0LL);
            //                       ▲
            //              No typecast required