28. String to Integer (atoi)

Medium · String

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm is as follows: 1. Read and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines the sign of the final result. 3. Read in next the characters until the next non-digit character or the end of the string. The rest of the string is ignored. 4. Convert these digits into an integer (e.g. "123" → 123, "0032" → 32). If no digits were read, the result is 0. 5. If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], clamp it to the range: if the result is less than -2147483648, return -2147483648; if the result is greater than 2147483647, return 2147483647.

Return the integer as the final result.

Examples

Example 1
Input: "42"
Output: 42
Explanation: The string "42" is converted to the integer 42.
Example 2
Input: "  -042"
Output: -42
Explanation: Leading whitespace is ignored, then '-' is read as the sign. The digits "042" are converted to 42, and the sign makes it -42.

Constraints