LeetCode #8 Medium

String to Integer (atoi)

Parse a string into a 32-bit integer the way C's atoi does: skip spaces, optional sign, digits until a non-digit, clamp to [−2³¹, 2³¹−1].

stringparsing
Open on LeetCode ↗
02

Intuition

💡

This is a tiny state machine: whitespace → sign → digits → stop. The only real trap is overflow — clamp when the accumulating value crosses the 32-bit boundary, checking before it grows out of range in fixed-width languages.

03

Approach

1

Three phases in order

Skip leading spaces only; read at most one sign; consume digits until the first non-digit ends parsing. Anything malformed before a digit → 0.

2

Accumulate and clamp

num = num*10 + digit. If it exceeds 2³¹−1, return the clamp (positive) or −2³¹ (negative). Python can check after; C/Java must check before multiplying.

3

Everything else is ignored

Trailing garbage after digits is fine — parsing simply stops.

04

Solution & live demo

python
1class Solution:
2 def myAtoi(self, s):
3 i, n = 0, len(s)
4 while i < n and s[i] == " ": i += 1
5 sign = 1
6 if i < n and s[i] in "+-":
7 sign = -1 if s[i] == "-" else 1
8 i += 1
9 num = 0
10 while i < n and s[i].isdigit():
11 num = num * 10 + int(s[i])
12 i += 1
13 num *= sign
14 return max(-2**31, min(2**31 - 1, num))
05

Edge cases

" -42"

Spaces skipped, sign captured → −42.

"4193 with words" / "words 42"

First: parses 4193 then stops. Second: no leading digit → 0.

"-91283472332"

Below INT_MIN → clamps to −2147483648.

06

Complexity

Time
O(n)
Space
O(1)
Single forward scan.