#8

String to Integer (atoi)

Medium Parsing with overflow clamp

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Parse an integer from a string: skip leading spaces, read an optional sign, read digits until a non-digit, and clamp the result to the 32-bit range.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: read an integer the way C's atoi does: spaces, sign, digits, then stop; clamp to int range.

Why this works: do the steps in order, and check for overflow before adding each digit.

Example: " -42abc"

skip spaces → '-' signdigits 4, 2 → 42, stop at 'a'→ -42

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using Integer.parseInt or a long without limit checks — very long digit strings still overflow a long.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon