String to Integer (atoi) solution explained

String to Integer (atoi) is solved with one left-to-right pass in four stages: skip leading spaces, read at most one + or - sign, read ASCII digits until the first non-digit, and clamp the value to the signed 32-bit range. The clamp is done before each digit is added, by checking result > (limit - digit) // 10, so no value wider than 32 bits is ever built. It runs in O(n) time and O(1) extra memory.

By Published 7 min read

The problem in plain words

You are handed a string and must read an integer off its front, the way the C library function atoi does. Leading space characters are ignored. Then there may be a single plus or minus sign. Then come decimal digits, and reading stops at the first character that is not a digit, whatever it is: a letter, a dot, a second sign or another space. Leading zeros are allowed and change nothing. If no digit was read, the answer is 0. If the digits describe a number outside the signed 32-bit range, the answer is the nearest limit, 2,147,483,647 or -2,147,483,648, rather than a wrapped or garbage value.

Examples computed with the code on this page (spaces shown as they appear)
InputOutputWhy
" -0019 apples"-19Spaces skipped, sign kept, leading zeros ignored, stop at the space
"8.75"8The dot ends the number
"+-7"0Only one sign is allowed; the minus is not a digit, so nothing was read
"pi 3"0A letter comes before any digit
" +3000000000"2147483647Too large, so it saturates at the maximum
"-2147483649"-2147483648One below the minimum, clamped
A tab, then "5"0Under the usual rule only the space character is skipped
Examples computed with the code on this page (spaces shown as they appear). Scroll sideways on a small screen.

That last row is worth raising before you code. Many statements of this problem skip only the plain space, while real atoi skips every whitespace character. Ask which one the interviewer wants. This page follows the space-only rule, and the code checks for exactly " " instead of calling a trim or strip helper, because those remove tabs and newlines too.

Why interviewers like it

There is no clever trick here. The question tests whether you can turn a messy specification into code that covers every case, and whether you think about overflow in a language with fixed-width integers. It is close to a real task: parsers for configuration files, command-line flags and network headers all do this. Interviewers watch for clarifying questions, a clean structure that mirrors the rules, and a test list that includes the awkward inputs. Candidates who start typing immediately tend to patch bugs one by one; candidates who list the stages first usually write it once.

Follow-ups you may hear

  • Skip all whitespace. Change the first loop's test to a whitespace check; nothing else moves.
  • Return an error instead of 0 or a clamp. Return a pair (value, ok) or raise, and say why a caller might prefer that; 0 is ambiguous because "0" also parses to 0.
  • Parse 64-bit values. Same structure, new limits.
  • Accept hexadecimal after 0x. Detect the prefix after the sign, then multiply by 16 and map a to f.
  • Parse a decimal number such as "-12.5e3". That becomes a real state machine with more states, which is the natural extension of the version below.

First version: find the digits, then convert

Walk an index past the spaces and the optional sign, remember where the digits start, walk to the end of the digit run, and hand that slice to the language's integer parser. Then clamp. It is short and easy to reason about. In Python the conversion can produce a number with hundreds of digits before the clamp trims it, which is fine in Python but not something you can do in C, Java or Go without a bigger type.

@@string-to-integer-atoi/slow.py@@
Python: scan for the digit run, convert it, clamp at the end. O(n) time, O(n) for the slice.

Avoid the tempting shortcut of calling int() or JavaScript's parseInt on the whole string. Python's int() rejects "12 apples" but accepts "1_000" and surrounding tabs; parseInt reads "0x1A" as 26 and skips leading tabs and newlines. Each disagrees with the rules in a different place, so you end up writing the scan anyway.

Expected version: a four-stage scan with a pre-push clamp

The pattern is a finite state machine written as consecutive loops. The states are: skipping spaces, expecting an optional sign, reading digits, done. Each loop consumes characters for one state and falls through to the next. Inside the digit loop, the clamp check runs before result * 10 + digit is computed. The push is safe only when result <= (limit - digit) / 10, and because result is a whole number you can compare it with the floor of that fraction. The limit is 2^31 - 1 for a positive number and 2^31 for a negative one, since the magnitude of the minimum is one larger than the maximum.

@@string-to-integer-atoi/fast.py@@
Python: one pass, clamp before overflow, ASCII digits only. O(n) time, O(1) memory.

The JavaScript version has the same shape. The s[i] >= "0" && s[i] <= "9" test compares one-character strings, which works because the ten digits are consecutive in Unicode. The final || 0 matters only for inputs like "-0", where -result would otherwise be negative zero.

@@string-to-integer-atoi/fast.js@@
JavaScript: the same four stages; the name avoids clashing with the built-in parseInt.

Cost

n is the length of the string
ApproachTimeExtra memoryNeeds a wide integer?
Scan, slice, convert, clampO(n)O(n) for the sliceYes, the converted value can be huge
Four-stage scan with pre-push clampO(n)O(1)No
Built-in parser on the whole stringO(n)DependsGives wrong answers on several inputs
n is the length of the string. Scroll sideways on a small screen.

Once the value saturates, the clamp version returns at once, so a string of a million digits stops after about eleven of them. The slicing version reads and converts the whole run first.

Edge cases to test out loud

  • The empty string and a string of only spaces: 0.
  • A lone sign, "+" or "-": 0, and the code must not read past the end.
  • Two signs in a row, in either order: 0.
  • "-0" and "+000": 0, with no negative zero in JavaScript.
  • Exactly 2147483647 and -2147483648, which must come back unchanged, and one past each, which must clamp.
  • A very long digit run, which must clamp instead of overflowing or slowing down.
  • Digits from other scripts, such as Arabic-Indic digits or a superscript two. Python's isdigit() accepts some of them, so the code compares against "0" and "9" instead.

Mistakes that cost points

  • Checking for overflow after multiplying, when a fixed-width language has already wrapped the value.
  • Using one limit for both signs and clamping -2147483648 to -2147483647.
  • Allowing a sign after the spaces and again after the first digit, as in "5-3", where reading should stop at the minus.
  • Skipping spaces between the sign and the digits; "- 5" gives 0.
  • Indexing s[i] without checking i < n after the sign, which crashes on "-" in some languages.
  • Returning early with the absolute value and forgetting to apply the sign.

Talking through it in the interview

Fictional example

Clarify first, then code the stages
Candidate
Before I write anything: do we skip only spaces or tabs and newlines too? And for an out-of-range number, do we clamp to the limit? I'll assume spaces only and clamping.
Candidate
I'll write it as four stages in order: spaces, one optional sign, digits, stop. Each is a short loop over the same index.
Candidate
For overflow I'll check before pushing each digit: result has to be at most the limit minus the digit, divided by ten. The limit is one bigger for negatives.
Candidate
Tests I'd run: empty, just a minus, plus-minus-seven, minus zero, both limits and one past each, and a long run of nines.

Reverse Integer uses the same check-before-push inequality on digits that come from a number instead of a string. Roman to Integer is another left-to-right string scan where a character's meaning depends on its neighbor. Zigzag Conversion is a string problem that rewards stating the rules precisely before writing loops.

Natively for practice

Specification-heavy questions are best practiced aloud, because the clarifying questions are half the grade. On Mac or Windows, Natively can read the prompt from a screenshot during a practice session, suggest which rules to confirm before coding, and propose awkward inputs for your test list. Its transcript of the mock lets you check afterwards whether you asked about whitespace and overflow before you started typing.

Questions people ask

How do you solve String to Integer (atoi)?

Scan once from the left: skip spaces, read one optional sign, read ASCII digits until a non-digit, and before adding each digit check whether the value would pass the 32-bit limit. If it would, return the limit.

What does atoi return when there are no digits?

It returns 0. That covers an empty string, a string of spaces, a lone sign, two signs in a row, and text that starts with a letter.

How do you handle overflow in atoi?

Clamp instead of wrapping. Before computing result * 10 + digit, compare result with (limit - digit) // 10, using 2^31 - 1 for positive numbers and 2^31 for negative ones, and return the matching limit if it is larger.

Can I use int() or parseInt for atoi?

Not on the whole string. Built-in parsers accept or reject different inputs than the problem's rules, such as underscores, hexadecimal prefixes or tabs, so you still need your own scan for the digit run.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP