String to Integer (atoi)

Skip whitespace, parse optional sign, consume digits with overflow clamp.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
string parsing math

Problem#

Implement a parser that converts a string to a 32-bit signed integer (clamp to [-2^31, 2^31-1] on overflow). Skip leading whitespace, parse optional sign, consume the digit run.

Examples#

  • "42"42.
  • " -42"-42; "4193 with words"4193; "words and 987"0.

Constraints#

  • 0 <= s.length <= 200.

Approach#

Skip whitespace. Consume optional sign. Parse digits, clamping at each step before multiplying by 10.

Solution#

String to Integer (atoi)
class Solution {
public:
int myAtoi(string s) {
int i = 0, n = s.size();
while (i < n && s[i] == ' ') ++i;
int sign = 1;
if (i < n && (s[i] == '+' || s[i] == '-')) {
if (s[i] == '-') sign = -1;
++i;
}
long long ans = 0;
while (i < n && isdigit(s[i])) {
ans = ans * 10 + (s[i] - '0');
if (sign * ans > INT_MAX) return INT_MAX;
if (sign * ans < INT_MIN) return INT_MIN;
++i;
}
return (int)(sign * ans);
}
};

Editorial#

Using long long for the accumulator lets us multiply by 10 and add a digit without immediate overflow; the per-step clamp catches any value beyond int range as it’s being built. Whitespace and sign are each parsed at most once.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.