When we implement add function by operator + in C++, sometimes we face over error - actually system does not show any error and that should be continuously increased, but there is a possibility to change into minus value suddenly.
You can see the same case when you compile and run by below code:
test.cpp
#include <iostream> using namespace std; int main() { int a; for(int b=0; b<1000000; b++) { cout << a << "\n"; a+= 10000000; } }
Below safe_add() function enables you to check overflow error:
safe_add.cpp
#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)