![]() |
VOOZH | about |
Given two integers a and b. The task is to design a function that adds two integers and detects overflow during the addition. If the sum does not cause an overflow, return their sum. Otherwise, return -1 to indicate an overflow.
Note: You cannot use type casting to a larger data type to check for overflow. Also, the function must handle both positive and negative integers correctly.
Examples:
Input: a = 1000000000, b = 1000000000
Output: 2000000000
Explanation: The sum 1000000000 + 1000000000 = 2000000000 is within the valid integer range, so no overflow occurs, and the function stores the result successfully.Input: a = -2000000000, b = -500000000
Output: -1
Explanation: The sum -2000000000 + (-5000000000) = -7000000000 exceeds the maximum limit of an integer (assuming 32 bit representation), causing an overflow.Input: a = -100, b = 100
Output: 0
Explanation: The sum -100 + 100 = 0 is within the valid integer range, so no overflow occurs, and the function stores the result successfully.
Table of Content
The idea is to detect overflow by observing how the sum behaves relative to the input values. The thought process is that overflow can only occur if both numbers have the same sign, but the sum has the opposite sign. The key observation is that in a typical integer representation, exceeding the maximum or minimum limit causes a wraparound effect, flipping the sign unexpectedly. By checking if this sign reversal happens, we can accurately determine overflow and return an error indicator.
2000000000
Time Complexity: O(1), due to constant number of operations (addition and comparisons).
Space Complexity: O(1), as only a few integer variables are used.
The idea remains the same as in the previous approach, checking for integer overflow while performing addition. Instead of relying on post-addition checks, we now prevent overflow before it happens by ensuring that the sum does not exceed Max Integer Value for positive numbers or go below Min Integer Value for negative numbers.
2000000000
Time Complexity: O(1), due to constant number of operations (addition and comparisons).
Space Complexity: O(1), as only a few integer variables are used.