String to Integer (atoi)

Medium

Topics
String

Turn the text s into a 32-bit signed integer by reading it strictly left to right:

  1. Skip any leading space characters (' ' only).
  2. Read at most one sign character, + or -. With no sign the number is positive.
  3. Read consecutive digits 0-9 and stop at the first character that is not a digit, or at the end. Leading zeros are allowed. If no digit was read, the value is 0.
  4. If the value falls outside [-2^31, 2^31 - 1], return the nearest bound instead.

Everything after the digits is ignored. Do not use a library parsing routine.

Example 1

-0071 apples
signdigitsignored
Four phases in a fixed order: skip leading spaces, take an optional sign, read digits, and stop at the first non-digit rather than failing. The result is then clamped to the 32-bit range — -71 here. Most wrong answers come from reordering those phases or clamping too late.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "   -0071 apples"
Output: -71

Example 2

x9
ignored
Input:  s = "x9"
Output: 0
Explanation: The first non-space character is not a sign or digit, so nothing is read.

Example 3

99999999999
digits
Input:  s = "99999999999"
Output: 2147483647
Explanation: Too large, so it is clamped.

Example 4

-+5
signignored
Input:  s = "-+5"
Output: 0
Explanation: Only one sign may be read; "+" is not a digit.

Constraints

  • 1 <= s.length <= 200
  • s consists of English letters, digits, spaces, and the characters + - .
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is a small state machine with three phases: spaces, sign, digits. Each phase consumes characters until its condition fails and then hands over to the next. The only subtle part is detecting overflow before it happens, since the language's own integer would overflow first.

Approach

  1. Advance an index past spaces.
  2. If the next character is + or -, record the sign and advance once.
  3. While the character is a digit, check overflow first: if value > (2^31 - 1 - d) / 10, return the clamp for this sign. Otherwise set value = value * 10 + d.
  4. Return sign * value.

Dry Run

s = "   -0071 apples"
  skip 3 spaces            now at '-'
  sign character '-'       sign = -1, advance
  digit '0'                value 0
  digit '0'                value 0
  digit '7'                value 7
  digit '1'                value 71
  stop at ' ', not a digit
answer -71
Four phases in a fixed order: spaces, then at most one sign, then digits, then
stop. Nothing is revisited, which is why the leading zeros need no special handling
at all -- they multiply 0 by 10 and add 0.
The order matters more than it looks:
  "x9"            -> 0      a non-digit before any digit ends it immediately
  "- 5"           -> 0      spaces are skipped BEFORE the sign, never after
  "+-12"          -> 0      at most one sign character is consumed
  "  +0 123"      -> 0      the scan stops at the space; the 123 is unreachable
  "2147483648"    -> 2147483647    clamped at the positive bound
  "-2147483648"   -> -2147483648   unchanged, because the negative bound is one
                                   further from zero than the positive one
That asymmetry is worth stating explicitly. The clamp is checked inside the loop,
against INT_MAX when positive and INT_MIN when negative, which is why
"-2147483648" survives while "2147483648" does not.

Complexity

  • Time — O(n): each character is read at most once.
  • Space — O(1): a few scalars.

Common Pitfalls

  • Clamping only after the loop works in Python but overflows in Java, C++ and JavaScript-style int arithmetic. Check before each multiply.
  • Skipping spaces after the sign is wrong: "- 5" is 0.
  • The negative clamp is -2^31, one further from zero than the positive one, so "-2147483648" must come back unchanged.

Full Solution — all languages

class Solution:
    def myAtoi(self, s):
        INT_MIN, INT_MAX = -2147483648, 2147483647
        i = 0
        while i < len(s) and s[i] == ' ':
            i += 1
        sign = 1
        if i < len(s) and s[i] in '+-':
            if s[i] == '-':
                sign = -1
            i += 1
        value = 0
        while i < len(s) and s[i].isdigit():
            value = value * 10 + (ord(s[i]) - 48)
            if sign == 1 and value > INT_MAX:
                return INT_MAX
            if sign == -1 and -value < INT_MIN:
                return INT_MIN
            i += 1
        return sign * value
SensAI
Beta
Tap the mic to stop voice mode