String to Integer (atoi)

Medium· parsing· simulation

Problem

Convert a string to a 32-bit signed integer the way C's atoi does: skip leading spaces, read an optional sign, then read digits until a non-digit appears. If there are no digits the result is 0, and results outside the 32-bit range are clamped to its bounds.

Examples

Input: s = " -0042abc"
Output: -42
Spaces are skipped, the sign is read, leading zeros vanish and parsing stops at "a".
Input: s = "9999999999"
Output: 2147483647
The value overflows, so it is clamped to 2^31 - 1.

Constraints

  • • 0 <= s.length <= 200
  • • s contains letters, digits, spaces, "+", "-" and "."

Hints & approach

Hint 1

Handle the phases in order: whitespace, sign, digits.

Hint 2

Build the number digit by digit as result * 10 + digit.

Hint 3

Check for overflow before multiplying, not after.

Approachtry the hints first

Use an index to walk the string: skip spaces, then consume at most one "+" or "-" to set the sign. While the current character is a digit, check whether result * 10 + digit would exceed 2^31 - 1 (compare against INT_MAX / 10 and the last digit); if so, return the clamped bound for the sign. Otherwise accumulate the digit. Return sign * result once a non-digit or the end is reached.

Time O(n) · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.