String to Integer (atoi)

Medium Solved

Description

Implement atoi which converts a string to a 32-bit signed integer (similar to C/C++ atoi).

  • Read in and ignore any leading whitespace.
  • Optional '+' or '-' sign.
  • Read in next characters until the next non-digit character or end of input; convert these digits to an integer.
  • If no digits were read, return 0.
  • Clamp the integer to the 32-bit signed integer range: [-2^31, 2^31 - 1].

Example 1:

Input: "42"

Output: 42

Example 2:

Input: " -42"

Output: -42

Example 3:

Input: "4193 with words"

Output: 4193

Note:

Runner reads a single line string from stdin and expects a single integer printed to stdout (e.g. input: -42 → output: -42).

Your Submissions

No submissions yet.

Discuss

Talk about parsing edge-cases, spaces, signs, overflow, and early termination rules.

Test Cases

Test Case 1
Test Case 2
Test Case 3
Test Case 4
Test Case 5