String to Integer (atoi)
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
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)