Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
String to Integer (atoi)
Problem
Convert a string to a 32-bit signed integer following these rules, in order:
- Skip any leading spaces (only the space character
' '). - Read an optional single
+or-sign. - Read consecutive digits until a non-digit or the end of the string. Leading zeros are allowed.
- Ignore everything after the digits.
- If no digits were read, the result is
0. - Clamp the result to the range
[-2^31, 2^31 - 1].
- The string can be empty or up to a couple hundred characters.
smay contain letters, digits, spaces,+,-, and..- Do not use built-in integer parsing that already implements these rules; the point is to write the state machine.
Examples
"77"→77;" -0088"→-88(spaces skipped, sign read, leading zeros ignored)."256zz9"→256;"5*3"→5;"hello 42"→0. Parsing stops at the first character that does not fit the current stage, and a sign after digits or letters is never read."-83214459999"→-2147483648(clamped);"-+7"→0, because only one sign character is permitted.
Hints
- Write down the stages as a sequence: whitespace, sign, digits, stop. Each stage consumes zero or more characters and never goes back.
- Accumulate
value = value * 10 + digit. Before doing so, check whether that step would exceed the bound; compare againstINT_MAX // 10andINT_MAX % 10. - In Python overflow does not happen, so you can accumulate freely and clamp at the end. Say why that would not work in C or Java, and show the pre-multiplication check anyway.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.