Implement Safe Integer Addition

Implement Safe Integer Addition

Hard C++ C++ Data Types 33 views
Explanation Complexity

Problem Statement

Add two integers while checking for overflow before it happens. This teaches defensive programming.
Logic: Check if addition exceeds INT_MAX before performing

Input Format

Two integers a and b.

Output Format

• Sum of a and b
OR

• Message: Overflow detected

Example

a = 2000000000
b = 2000000000
Overflow detected

Constraints

• Use 32-bit int

• Check overflow before addition

Concept Explanation

Integer overflow happens when the result goes beyond the allowed range of int.
So we must check limits before adding.

Step-by-Step Explanation

1.Take integers a and b.

2.If b > 0 and a > INT_MAX - b:

• Overflow will happen.

3.If b < 0 and a < INT_MIN - b:

• Underflow will happen.

4.If no overflow or underflow:

• Safely calculate a + b.

5.Print the result or overflow message.

Concept Explanation

Integer overflow happens when the result goes beyond the allowed range of int.
So we must check limits before adding.

Step-by-Step Explanation

1.Take integers a and b.

2.If b > 0 and a > INT_MAX - b:

• Overflow will happen.

3.If b < 0 and a < INT_MIN - b:

• Underflow will happen.

4.If no overflow or underflow:

• Safely calculate a + b.

5.Print the result or overflow message.

Input / Output Format

Input Format
Two integers a and b.
Output Format
• Sum of a and b
OR

• Message: Overflow detected
Constraints
• Use 32-bit int

• Check overflow before addition

Examples

Input:
a = 2000000000 b = 2000000000
Output:
Overflow detected

Example Solution (Public)

C++
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;
    }
}

Official Solution Code

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;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.