Description
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
- Whitespace: Ignore any leading whitespace (“ “).
- Signedness: Determine the sign by checking if the next character is ‘-‘ or ‘+’, assuming positivity if neither present.
- Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
- Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.
Return the integer as the final result.
Example 1:1
2Input: "42"
Output: 42
Example 2:1
2
3
4Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which indicates an negative sign.
Then take the rest of the string after the sign. "42" is the integer part.
Example 3:1
2
3Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a digit.
Example 4:1
2
3
4Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which indicates an invalid input.
Example 5:1
2
3
4Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore, the integer overflows and becomes negative. The function should return -2147483648.
Constraints:
- 0 <= s.length <= 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ‘ ‘, ‘+’, ‘-‘, and ‘.’.
Approach
1 | class Solution: |







