~/problems / Iterators & parsers / Parsers and interpreters

String to Integer (atoi)

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

An old form reader turns whatever people typed into a 32-bit integer. It never rejects input: it reads as much of a number as it can find at the start and ignores the rest.

Write string_to_int(s: str) -> int that follows these rules, in order:

  1. Skip leading space characters ' '. Only spaces are skipped; any other character ends this step.
  2. If the next character is '+' or '-', read it as the sign. At most one sign is allowed. With no sign the number is positive.
  3. Read digits 0-9 until the first character that isn't a digit, or the end of the string. Leading zeros are fine. Everything after the digits is ignored.
  4. If step 3 read no digits at all, the answer is 0.
  5. If the number is outside the 32-bit range [-2^31, 2^31 - 1], clamp it: anything below -2147483648 becomes -2147483648, and anything above 2147483647 becomes 2147483647.
string_to_int("  -0042 apples")     # -42  (spaces, sign, digits; " apples" is ignored)
string_to_int("+17")                # 17
string_to_int("3.99")               # 3    (the "." stops the digits)
string_to_int("about 12")           # 0    ("a" is not a space, sign or digit)
string_to_int("-+5")                # 0    (a second sign is not a digit)
string_to_int("  - 5")              # 0    (no digits right after the sign)
string_to_int("98765432109")        # 2147483647   (too big, clamped)
string_to_int("-2147483649")        # -2147483648  (too small, clamped)

Constraints: 0 <= len(s) <= 200; s holds English letters, digits, spaces, '+', '-' and '.'.

In C++ and Java, the digits can run far past what even a 64-bit integer holds, so stop growing the number once it is out of range.

Show hint

walk an index through the string, one step per rule. Before adding each digit, check whether the result is already past the limit.

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc