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.
- 0 <= s.length <= 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
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.
"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.
Approach
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).
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.
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.
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.
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.
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.
Code in Python, C++ and Java
+ or -, so there are no spaces to skip and no sign to read. The number counts as positive, and the next phase is digits.+ or -, so there are no spaces to skip and no sign to read. The number counts as positive, and the next phase is digits.Common pitfalls
Handing the string to a built-in parser
return int(s.strip())
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
num = num * 10 + d
if num > INT_MAX:
return INT_MAXif num > INT_MAX // 10 or (num == INT_MAX // 10 and d > 7):
return INT_MAX if sign == 1 else INT_MIN
num = num * 10 + dPython'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
return INT_MAX
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
while i < n and s[i] in "+-":
if s[i] == "-":
sign = -sign
i += 1if i < n and s[i] in "+-":
if s[i] == "-":
sign = -1
i += 1Only 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.
Edge cases
"" or " "The space loop runs i to the end, every later check fails on i < n, and sign * num is 0.
"- 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.
Complexity
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.