String to Integer (atoi)
Implement myAtoi(s) which converts a string to a 32-bit signed integer:
- Skip leading whitespace
- Read an optional '+' or '-' sign
- Read digits until a non-digit character or end of string
- Clamp the result to the 32-bit signed integer range: [-2^31, 2^31 - 1]
- Return 0 if no digits were read
Example
-42
-42
- The function skips leading whitespace, but since there's none in the input
-42, it proceeds to the next step. - It reads the optional sign, which is
-in this case, indicating a negative number. - The function then reads the digits
42and converts them to an integer: . - Since is within the 32-bit signed integer range , the result is not clamped and is returned as is.
- The final output is
-42.
Constraints
- 0 <= len(s) <= 200
- s consists of English letters, digits, ' ', '+', '-', '.'