Last Updated: 16 Jul, 2020

Check Integer Overflow

Easy
Asked in companies
ThalesThoughts2Binary Consulting & SolutionsAmdocs

Problem statement

You have given two 32 bit signed integers, and you have to check if their multiplication will overflow 32 bit signed integer or not.

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold.

Input format :
The first line of input contains the first 32 bit signed integer 'A'.

The second line of input contains the second 32 bit signed integer 'B'.
Output format :
The only line of output contains 'true' if the multiplication of 'A' and 'B' is overflowing in 32 bit signed integer or 'false' otherwise.
Note:
Return the expected boolean value from the function, no need to print anything.
Constraints :
-2^31 <= A <= 2^31 - 1
-2^31 <= B <= 2^31 - 1

where 'A' and 'B' are the given integers.
Time Limit: 0.5 sec.
Note :
Try to solve this problem assuming you can only have 32 bit signed integers (Without using any typecasting to other datatypes)

Approaches

01 Approach

  1. Typecast either of the operands to a type that can hold a really large number(exceeding the limits of integer).
  2. Take a product of the operands now
  3. Check the result of the operation:
    1. If it is not in the range of integers, there is an overflow.
    2. It is, then no overflow.

02 Approach

Let’s say the two integers being multiplied together are ‘a’ and ‘b’. 

There will be three possibilities:

  • a = 0: If a is zero, then a*b will be 0 and thus there will be no overflow.
  • a > 0: The simple way to check for overflow will be to check whether a*b > INT_MAX. But if a*b were to overflow then this comparison wouldn’t be of much help. Also, since we are confined to a 32-bit environment, we can’t store a and b in 64 or 128 bits. So, to circumvent this constraint, we will comparisons depending on b's sign
    • b ≥ 0:  We will compare b with INT_MAX / a. If b is greater, then a*b will overflow, otherwise, it will not.
    • b < 0: We will compare b with INT_MIN/a. If b is smaller, then a*b will overflow, otherwise, it will not.
  • a < 0: For this case, we will comparisons depending on b's sign:
    • b ≥ 0: We will compare b with INT_MIN/a. If b is greater, then a*b will overflow, otherwise, it will not.
    • b < 0: We will compare b with INT_MAX/a. If b is smaller, then a*b will overflow, otherwise, it will not.