String to Integer (atoi)

MediumStringsparsing state machine

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement a function that converts a string into a 32-bit signed integer, mimicking the behavior of the classic C atoi routine. Read the input string s from left to right and apply the following steps in order: 1. **Skip leading whitespace.** Advance past any number of leading space (' ') characters. 2. **Read an optional sign.** If the next character is '+' or '-', record the sign and move one character forward. If neither appears, assume the number is positive. 3. **Read the digits.** Consume consecutive numeric characters ('0'–'9') and assemble them into an integer. Stop as soon as a non-digit character is reached or the string ends. If no digits were read at all, the result is 0. 4. **Apply the sign** to the assembled number. 5. **Clamp to the 32-bit signed range.** The result must stay within [-2^31, 2^31 - 1], i.e. [-2147483648, 2147483647]. If the parsed value falls below the minimum, return -2147483648; if it exceeds the maximum, return 2147483647. Any characters that appear after the digits (or any leading characters that are not whitespace, a sign, or a digit) are ignored and have no effect beyond stopping the parse. Return the final integer.

Examples

Input: s = "42"
Output: 42
No whitespace or sign; the digits "42" parse directly to 42.
Input: s = " -042"
Output: -42
Three leading spaces are skipped, the '-' sets a negative sign, and "042" reads as 42, giving -42.
Input: s = "words and 987"
Output: 0
The first non-whitespace character 'w' is not a sign or digit, so parsing stops immediately with no digits read, yielding 0.
Input: s = "-91283472332"
Output: -2147483648
The full value -91283472332 is below the 32-bit minimum, so it is clamped to -2147483648.

Constraints

  • `0 <= s.length <= 200`
  • `s` consists of English letters (lower-case and upper-case), digits (`0`-`9`), `' '`, `'+'`, `'-'`, and `'.'`.
  • The final answer must be clamped to the 32-bit signed integer range `[-2147483648, 2147483647]`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.