You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Below code simple check overflow in C++

#define INT_MAX 2147483647
#define INT_MIN -2147483648

    int safe_add(int &sum, int a, int b) {
        if (abs(a)>INT_MAX-abs(b)) {
            cout << "overflow : " << a << "+" << b << endl;
            return 0;
        }
        
        sum = a + b;
        
        return 1;
    }

Time Complexity : O(1)
Space Complexity: O(1)

  • No labels