String to Integer (atoi)

Medium~15 min

Implement a function that converts a string to a 32-bit signed integer, similar to C's atoi function.

The algorithm is as follows:

  1. Skip leading whitespace — ignore any spaces at the start of the string
  2. Check for sign — if the next character is '+' or '-', read it and determine the sign. Assume positive if neither is present.
  3. Read digits — read characters while they are digits ('0' through '9'). Stop at the first non-digit character or end of string.
  4. Convert to integer — convert the collected digits into an integer, applying the sign.
  5. Clamp to 32-bit range — if the result is outside [-2^31, 2^31 - 1], clamp it to the nearest boundary.

If no digits are read, return 0.

Examples

Example 1
Input: s = "42"
Output: 42
Explanation: No whitespace, no sign, digits "42" → 42.
Example 2
Input: s = " -42"
Output: -42
Explanation: Leading whitespace is skipped, sign is negative, digits "42" → -42.
Example 3
Input: s = "4193 with words"
Output: 4193
Explanation: Digits "4193" are read, then parsing stops at the space.

Constraints

  • 0 <= s.length <= 200
  • s consists of English letters, digits, spaces, and the characters '+' and '-'.
  • Result must be clamped to [-2^31, 2^31 - 1].
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run