String to Integer (atoi) (LeetCode 8): Solution and Explanation
Convert a string to a 32-bit signed integer the way C's atoi does: skip leading spaces, read one optional sign, read digits until something else appears, and clamp the value to the range [-2^31, 2^31 - 1].
Intuition
The rules describe a fixed order of stages. First come spaces, then at most one sign, then digits. Once the digits stop, nothing after them matters. One index that only moves forward handles all three stages.
Building the number is the usual decimal trick: result = result * 10 + digit for each digit read. Leading zeros take care of themselves because 0 * 10 + 0 is still 0.
The real trap is overflow. In Java, C++, C# and Go a 32-bit int silently wraps when it grows past 2^31 - 1, so you must decide before multiplying whether the next step would overflow. Rearranging result * 10 + digit > INT_MAX gives result > (INT_MAX - digit) / 10, which uses only values that fit.
When that test fires, the true value is out of range no matter what digits follow, so return INT_MAX for a positive sign or INT_MIN for a negative sign immediately. A magnitude of exactly 2^31 with a minus sign also lands on INT_MIN, which is the right answer.
Approach: Single-pass parse with an overflow guard
- Set
i = 0and move it past every leading space. - If
s[i]is'+'or'-', setsignaccordingly and move past it. Otherwisesign = 1. - Set
result = 0. Whiles[i]is a digit, computedigit. Ifresult > (INT_MAX - digit) / 10, returnINT_MAXwhensign = 1andINT_MINotherwise. - Otherwise update
result = result * 10 + digitand move on. - When the digits end, return
sign * result.
Step-by-step example
s = " -042"
- Indices 0, 1 and 2 are spaces, so
imoves to 3. s[3]is'-', sosign = -1andibecomes 4.- Digit 0: the limit is
(2147483647 - 0) / 10 = 214748364, and 0 is below it, soresult = 0. - Digit 4 gives
result = 4, and digit 2 givesresult = 42. Both pass the overflow check easily. ireaches the end of the string, so return-1 * 42 = -42.
Code: Python, Java, C++
1class Solution:
2 def myAtoi(self, s: str) -> int:
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 sign = -1 if s[i] == '-' else 1
10 i += 1
11 result = 0
12 while i < n and '0' <= s[i] <= '9':
13 digit = ord(s[i]) - ord('0')
14 if result > (INT_MAX - digit) // 10:
15 return INT_MAX if sign == 1 else INT_MIN
16 result = result * 10 + digit
17 i += 1
18 return sign * result1class Solution {
2 public int myAtoi(String s) {
3 int i = 0, n = s.length();
4 while (i < n && s.charAt(i) == ' ') i++;
5 int sign = 1;
6 if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
7 sign = s.charAt(i) == '-' ? -1 : 1;
8 i++;
9 }
10 int result = 0;
11 while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
12 int digit = s.charAt(i) - '0';
13 if (result > (Integer.MAX_VALUE - digit) / 10) {
14 return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
15 }
16 result = result * 10 + digit;
17 i++;
18 }
19 return sign * result;
20 }
21}1class Solution {
2public:
3 int myAtoi(string s) {
4 int i = 0, n = s.size();
5 while (i < n && s[i] == ' ') i++;
6 int sign = 1;
7 if (i < n && (s[i] == '+' || s[i] == '-')) {
8 sign = s[i] == '-' ? -1 : 1;
9 i++;
10 }
11 int result = 0;
12 while (i < n && s[i] >= '0' && s[i] <= '9') {
13 int digit = s[i] - '0';
14 if (result > (INT_MAX - digit) / 10) {
15 return sign == 1 ? INT_MAX : INT_MIN;
16 }
17 result = result * 10 + digit;
18 i++;
19 }
20 return sign * result;
21 }
22};Time and space complexity
O(n)
The index moves forward one character at a time and never backs up, so each character is examined at most once.
O(1)
Only the index, the sign and the running result are stored.
Other approaches
Accumulate in a 64-bit integer (time O(n), space O(1))
Use a long for result and clamp as soon as it exceeds 2^31. This is simpler, but it relies on a wider type, and with 200 digits even a 64-bit value would overflow unless you stop early, so you still need an early exit.
Regular expression (time O(n), space O(n))
Match ^ *[+-]?\d+ and convert the match with the language's big-number parser, then clamp. It is short in Python, but it hides the overflow logic interviewers want to see.
Common mistakes
- Checking for overflow after multiplying. In 32-bit languages the value has already wrapped to a negative number by then.
- Skipping all whitespace (tabs, newlines) instead of only
' '. The rules only treat the space character as skippable. - Accepting more than one sign, as in
"+-12". After one sign the next character must be a digit, otherwise the answer is 0. - Returning
-0in JavaScript for inputs like"-0".sign * 0is-0, which some comparisons print differently; normalise it to 0.
Frequently asked questions
Why compare against (INT_MAX - digit) / 10 instead of INT_MAX / 10?
The single comparison result > (INT_MAX - digit) / 10 covers both cases at once: a result that is already too big, and a result equal to INT_MAX / 10 whose next digit pushes it over. Integer division keeps it exact.
How does -2147483648 avoid being clamped wrongly?
When the magnitude reaches 2147483648 the check fires because it exceeds INT_MAX, and the negative sign returns INT_MIN, which equals -2147483648. So the clamp gives the right value.
What if the string has digits after a letter?
They are ignored. Parsing stops at the first non-digit after the optional sign, so "1337c0d3" returns 1337.
Does a decimal point count?
No. '.' is just a non-digit, so "3.14" returns 3.