String To Integer Atoi
Algorithm/String
Intuition
The task is to implement a function that converts a string to a 32-bit signed integer. This requires handling leading spaces, optional signs (+
or -
), numeric characters, and discarding invalid characters after the valid integer part. Additionally, the resulting integer should be clamped within the 32-bit signed integer range.
Approach
Below is the step-by-step breakdown of the approach:
- Trim Leading Spaces:
- Use a regular expression to match the valid pattern for the integer conversion. The pattern looks for:
- Any leading whitespace (
^\s*
). - An optional sign (
[-+]?
). - A sequence of digits (
\d+
).
- Any leading whitespace (
- Use a regular expression to match the valid pattern for the integer conversion. The pattern looks for:
- Parse the Matched Integer:
- If the input string matches the pattern, extract the numeric part and convert it to an integer.
- Check the sign captured from the match. If the sign is negative, multiply the number by
-1
.
- Clamp the Result within 32-bit Range:
- The integer should be clamped between
-2^31
and2^31 - 1
, useMath.max()
andMath.min()
to enforce this constraint.
- The integer should be clamped between
- Return the Result:
- If the input string doesn't match the pattern, return
0
. - Otherwise, return the clamped integer.
- If the input string doesn't match the pattern, return
Complexity
- Time Complexity: , the regular expression match and numeric operations are constant time.
- Space Complexity: , we only store a few variables and constants.