String to Integer (atoi)
Medium
Topics
Turn the text s into a 32-bit signed integer by reading it strictly left to right:
- Skip any leading space characters (
' 'only). - Read at most one sign character,
+or-. With no sign the number is positive. - Read consecutive digits
0-9and 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 is0. - 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
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
ignored
Input: s = "x9" Output: 0 Explanation: The first non-space character is not a sign or digit, so nothing is read.
Example 3
digits
Input: s = "99999999999" Output: 2147483647 Explanation: Too large, so it is clamped.
Example 4
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
- Advance an index past spaces.
- If the next character is
+or-, record the sign and advance once. - While the character is a digit, check overflow first: if
value > (2^31 - 1 - d) / 10, return the clamp for this sign. Otherwise setvalue = value * 10 + d. - 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 * valueimport java.util.*;
class Solution {
public int myAtoi(String s) {
final long INT_MIN_V = -2147483648L, INT_MAX_V = 2147483647L;
int i = 0;
while (i < s.length() && s.charAt(i) == ' ') i++;
long sign = 1;
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
if (s.charAt(i) == '-') sign = -1;
i++;
}
long value = 0;
while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
value = value * 10 + (s.charAt(i) - '0');
if (sign == 1 && value > INT_MAX_V) return (int) INT_MAX_V;
if (sign == -1 && -value < INT_MIN_V) return (int) INT_MIN_V;
i++;
}
return (int) (sign * value);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int myAtoi(string s) {
const long long INT_MIN_V = -2147483648LL, INT_MAX_V = 2147483647LL;
size_t i = 0;
while (i < s.size() && s[i] == ' ') i++;
long long sign = 1;
if (i < s.size() && (s[i] == '+' || s[i] == '-')) {
if (s[i] == '-') sign = -1;
i++;
}
long long value = 0;
while (i < s.size() && isdigit((unsigned char)s[i])) {
value = value * 10 + (s[i] - '0');
if (sign == 1 && value > INT_MAX_V) return (int)INT_MAX_V;
if (sign == -1 && -value < INT_MIN_V) return (int)INT_MIN_V;
i++;
}
return (int)(sign * value);
}
};/**
* @param {string} s
* @return {number}
*/ var myAtoi = function(s) {
const INT_MIN = -2147483648, INT_MAX = 2147483647;
let i = 0;
while (i < s.length && s[i] === ' ') i++;
let sign = 1;
if (i < s.length && (s[i] === '+' || s[i] === '-')) {
if (s[i] === '-') sign = -1;
i++;
}
let value = 0;
while (i < s.length && s[i] >= '0' && s[i] <= '9') {
value = value * 10 + (s.charCodeAt(i) - 48);
if (sign === 1 && value > INT_MAX) return INT_MAX;
if (sign === -1 && -value < INT_MIN) return INT_MIN;
i++;
}
return sign * value;
};