Check Integer Overflow

Easy
0/40
Average time to solve is 24m
profile
Contributed by
1 upvote
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.

Detailed explanation ( Input/output format, Notes, Images )
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)
Sample Input 1 :
127842721 
9
Sample Output 1 :
false
Explanation For Sample Output 1:
The product of the given two numbers is 1150584489, which is less than 2^31. Hence the output is false.
Sample Input 2 :
-1799120 
-2323232
Sample Output 2 :
true
Sample Input 3 :
-78921277 
1927279
Sample Output 3 :
true
Hint

Think of the possibilities where the operation may result in an overflow.

Approaches (2)
Typecasting
  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.
Time Complexity

O(1).

 

Since multiplying two numbers takes constant time.

Space Complexity

O(1).

 

Constant space is used.

Code Solution
(100% EXP penalty)
Check Integer Overflow
Full screen
Console