Coding · should-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

String to Integer (atoi)

mediumstringparsing

Problem

Convert a string to a 32-bit signed integer following these rules, in order:

  1. Skip any leading spaces (only the space character ' ').
  2. Read an optional single + or - sign.
  3. Read consecutive digits until a non-digit or the end of the string. Leading zeros are allowed.
  4. Ignore everything after the digits.
  5. If no digits were read, the result is 0.
  6. Clamp the result to the range [-2^31, 2^31 - 1].
  • The string can be empty or up to a couple hundred characters.
  • s may 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

  1. Write down the stages as a sequence: whitespace, sign, digits, stop. Each stage consumes zero or more characters and never goes back.
  2. Accumulate value = value * 10 + digit. Before doing so, check whether that step would exceed the bound; compare against INT_MAX // 10 and INT_MAX % 10.
  3. 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