LeetCode #8 Medium

String to Integer (atoi)

String to Integer (atoi) is LeetCode 8 (Medium). Write myAtoi(s), which turns the start of the string s into a 32-bit signed integer by reading it in this order:

1. Skip any spaces at the front. 2. Read one optional + or -. With no sign, the number is positive. 3. Read digits until a character that is not a digit, or the end of the string. Leading zeros are fine. If no digit is read, the answer is 0. 4. If the number is outside [−2³¹, 2³¹ − 1], return the nearest end of that range.

The string has at most 200 characters, so one pass is enough. The difficulty is following the rules in order and never letting the number overflow while you build it.

Constraints
  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
stringparsing
Open on LeetCode ↗
02

Intuition

The rules form four phases that always run in the same order: spaces, sign, digits, stop. Each character either belongs to the current phase or moves you to a later one, and you never go back, so a space after the sign simply ends the number.

The real danger is overflow. Building the number as num * 10 + d can pass 2³¹ − 1 = 2147483647, and a 32-bit int would wrap round before you could compare it. So test before you add the digit: the new value is too big exactly when num > 214748364, or num == 214748364 and d > 7. If the test fires, return the limit for the sign straight away.

How to spot this pattern

"Turn text into a number by these rules" is a parsing task, not a search for a clever algorithm. Interviewers ask you to implement atoi to see whether you follow a spec exactly and guard the arithmetic. The same skeleton (skip, sign, digits, range check) shows up in Valid Number, Reverse Integer and any hand-written parser, so the habit to learn is checking a limit before the arithmetic that could break it.

03

Approach

Try it first

Before reading on, list the phases the string goes through and decide what each kind of character does in each phase. Then work out, without ever storing a number larger than 2³¹ − 1, how to tell that the next digit would push you past it. Aim for O(n).

1

Skip the spaces at the front

Move an index i forward while s[i] is a space. Only the front is skipped: once any other character has been seen, a space is just a character that ends the number.

2

Read at most one sign

If s[i] is + or -, set sign to 1 or −1 and move past it once. A second sign is not a digit, so the digit loop stops on it and the answer is 0.

3

Read digits until one is missing

While s[i] is a digit, turn it into d = s[i] − '0' and add it as num = num * 10 + d. The first non-digit ends the loop, and whatever follows it is ignored rather than treated as an error.

4

Test for overflow before adding the digit

If num > 214748364, or num == 214748364 and d > 7, then num * 10 + d would be larger than 2147483647. Return 2³¹ − 1 if the sign is positive and −2³¹ if it is negative. Testing first means num itself never leaves the 32-bit range.

5

Apply the sign

When the loop ends without overflow, return sign * num. If no digit was read, num is still 0, so strings like "-" or "abc" give 0 with no extra check.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def myAtoi(self, s):
▶3 INT_MAX, INT_MIN = 2**31 - 1, -(2**31)
▶4 i, n = 0, len(s)
▶5 while i < n and s[i] == " ":
▶6 i += 1
▶7 sign = 1
▶8 if i < n and s[i] in "+-":
▶9 if s[i] == "-":
▶10 sign = -1
▶11 i += 1
▶12 num = 0
▶13 while i < n and s[i].isdigit():
▶14 d = ord(s[i]) - ord("0")
▶15 if num > INT_MAX // 10 or (num == INT_MAX // 10 and d > 7):
▶16 return INT_MAX if sign == 1 else INT_MIN
▶17 num = num * 10 + d
▶18 i += 1
▶19 return sign * num
spacessigndigitsstop␣i␣␣-42abcsign+num0testno digit to testchar 0 is a space → skip it
i0a space
Spaces are only allowed at the front, and they mean nothing, so move past this one. Once any other character appears, a space will end the number instead.
spacessigndigitsstop␣␣i␣-42abcsign+num0testno digit to testchar 1 is a space → skip it
i1a space
Spaces are only allowed at the front, and they mean nothing, so move past this one. Once any other character appears, a space will end the number instead.
spacessigndigitsstop␣␣␣i-42abcsign+num0testno digit to testchar 2 is a space → skip it
i2a space
Spaces are only allowed at the front, and they mean nothing, so move past this one. Once any other character appears, a space will end the number instead.
spacessigndigitsstop␣␣␣-i42abcsign−num0testno digit to test'-' is a sign → number is negative
i3
sign-1
The first non-space character is -. Read it once and move on: from here only digits can follow, so a second sign or a space would end the number.
spacessigndigitsstop␣␣␣-4i2abcsign−num4test0<214748364digit 4 is safe → number is 4
d4
num0 → 4
Before adding 4, compare 0 with 214748364. It is smaller, so even after × 10 the value fits in 32 bits. Then 0 × 10 + 4 = 4.
spacessigndigitsstop␣␣␣-42iabcsign−num42test4<214748364digit 2 is safe → number is 42
d2
num4 → 42
Before adding 2, compare 4 with 214748364. It is smaller, so even after × 10 the value fits in 32 bits. Then 4 × 10 + 2 = 42.
spacessigndigitsstop␣␣␣-42aibcsign−num42testnothing left to add'a' is not a digit → stop
i6'a'
a is not a digit, so the number ends here. Everything after it is ignored, not treated as an error.
spacessigndigitsstop␣␣␣-42abcsign−num42→−42testno overflowanswer: −42
return-42
No digit pushed the value past the limit, so apply the sign: −1 × 42 = -42.
05

Common pitfalls

Handing the string to a built-in parser

✗ Wrong
return int(s.strip())
✓ Right
while i < n and s[i].isdigit():
    ...

The built-in parsers reject anything after the number. On "4193 with words" Python's int() raises ValueError and Java's Integer.parseInt throws, but the expected answer is 4193.

Testing for overflow after the multiply

✗ Wrong
num = num * 10 + d
if num > INT_MAX:
    return INT_MAX
✓ Right
if num > INT_MAX // 10 or (num == INT_MAX // 10 and d > 7):
    return INT_MAX if sign == 1 else INT_MIN
num = num * 10 + d

Python's big integers hide this, but with a 32-bit int in Java, "2147483648" makes 214748364 * 10 + 8 wrap round to −2147483648, the test num > INT_MAX is false, and the code returns −2147483648 instead of 2147483647. In C++ the same overflow is undefined behaviour.

Clamping to the top limit for both signs

✗ Wrong
return INT_MAX
✓ Right
return INT_MAX if sign == 1 else INT_MIN

The overflow branch must look at the sign. On "-91283472332" the answer is −2147483648, not 2147483647.

Reading more than one sign

✗ Wrong
while i < n and s[i] in "+-":
    if s[i] == "-":
        sign = -sign
    i += 1
✓ Right
if i < n and s[i] in "+-":
    if s[i] == "-":
        sign = -1
    i += 1

Only one sign is allowed. On "+-12" the loop happily reads both signs and returns −12, but the second sign is not a digit, so the correct answer is 0.

06

Edge cases

Empty or only spaces, e.g. "" or " "

The space loop runs i to the end, every later check fails on i < n, and sign * num is 0.

A space between the sign and the digits, e.g. "- 42"

After the sign the code is in the digit loop, and a space is not a digit, so it stops at once and returns 0.

07

Complexity

Time
O(n)
Space
O(1)
Each character is read at most once, and the loop stops at the first character that cannot be part of the number. Only an index, the sign and the number are stored.
08

String to Integer (atoi) FAQ

Why is the overflow test d > 7?

2³¹ − 1 is 2147483647, and its last digit is 7. When num is exactly 214748364, the new value num * 10 + d stays within the limit for d from 0 to 7 and goes over for 8 or 9. When num is already above 214748364, any digit goes over.

The negative side reaches 2147483648. Doesn't the test need a special case for it?

No. "-2147483648" does trip the test on its final 8, but the clamp then returns −2³¹, which is −2147483648, the exact value. Every larger negative number also lands on −2³¹, so one test covers both signs.

Can I use a 64-bit long and clamp at the end?

Only if you clamp after every digit. The string can hold up to 200 digits, so "99999999999999999999" (20 nines) already overflows a 64-bit long before the loop ends. Checking after each digit, as soon as the value passes 2³¹ − 1, keeps a long safe.

Does this skip tabs and newlines like C's atoi?

No. C's atoi skips any whitespace, but this problem only means the space character ' ', and the input never contains tabs or newlines.