Practice/Meta/Leetcode 8. String to Integer (atoi)
Leetcode 8. String to Integer (atoi)
CodingMust
Problem
Implement a function that converts a string to a 32-bit signed integer, similar to how programming languages parse numeric strings. Your implementation should handle various edge cases including whitespace, optional signs, and overflow conditions.
The parsing process follows these rules:
- Ignore any leading whitespace characters
- Check if the next character is a '+' or '-' sign to determine the number's sign (positive is assumed if neither is present)
- Read consecutive digit characters until a non-digit is encountered or the end of the string is reached
- Convert the parsed digits into an integer
- If no valid digits were read, return 0
- If the integer exceeds the 32-bit signed integer range [-2³¹, 2³¹ - 1], clamp it to the appropriate boundary
Requirements
- Ignore leading whitespace in the input string
- Handle an optional '+' or '-' sign immediately after whitespace
- Parse contiguous digit characters and stop at the first non-digit
- Return 0 if no valid conversion can be performed
- Clamp the result to the range [-2147483648, 2147483647]
- Only the initial portion of the string is considered (stop at first non-digit after optional sign)
Constraints
- 0 ≤= s.length ≤= 200
- s consists of English letters (lower-case and upper-case), digits (0-9), spaces, '+', '-', and '.'
- The valid integer portion (if any) will not have leading zeros except for the number 0 itself
Examples
Example 1:
Input: s = "42" Output: 42 Explanation: The string contains only the number 42 with no extra characters.
Example 2:
Input: s = " -42" Output: -42 Explanation: After removing leading spaces, the sign is '-' and the number is 42.
Example 3:
Input: s = "4193 with words" Output: 4193 Explanation: Parsing stops at the space character after reading "4193".
Example 4:
Input: s = "words and 987" Output: 0 Explanation: The first non-whitespace character 'w' is not a digit or sign, so no conversion is possible.
Example 5:
Input: s = "-91283472332" Output: -2147483648 Explanation: The number underflows the 32-bit range, so it is clamped to -2^31.