Detect Integer Overflow

Medium~15 min

Given a string representation of an integer (with an optional leading + or - sign and no spaces), determine if it overflows a 32-bit signed integer range.

Return:

  • 1 if the number is greater than 2^31 - 1 (positive overflow)
  • -1 if the number is less than -2^31 (negative overflow)
  • 0 if the number is within the 32-bit signed integer range [-2^31, 2^31 - 1]

You may assume the input is a valid integer string (digits only, with an optional leading sign). The input will not be empty.

Examples

Example 1
Input: s = "2147483647"
Output: 0
Explanation: 2^31 - 1 = 2147483647, which is exactly at the upper bound — in range.
Example 2
Input: s = "2147483648"
Output: 1
Explanation: One more than the maximum 32-bit signed integer — positive overflow.
Example 3
Input: s = "-2147483649"
Output: -1
Explanation: One less than the minimum 32-bit signed integer — negative overflow.

Constraints

  • 1 <= s.length <= 20
  • s consists of digits and optionally a leading '+' or '-' sign.
  • s represents a valid integer (no spaces, no letters).
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run