Implement Safe Integer Addition
C++
Hard
7 views
Problem Description
Add two integers while checking for overflow before it happens. This teaches defensive programming.
Logic: Check if addition exceeds INT_MAX before performing
Official Solution
void question11_safe_addition() {
int a = 2000000000;
int b = 200000000;
int maxInt = 2147483647;
if(a > maxInt - b) {
cout << "Addition would cause overflow!" << endl;
} else {
int sum = a + b;
cout << "Safe sum: " << sum << endl;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!