String to Integer (atoi)
The key idea
[-2147483648, 2147483647] the moment it would overflow, so you never need a wider integer type.Problem
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:
1. Whitespace: ignore any leading whitespace (' ').
2. Signedness: determine the sign by checking if the next character is '-' or '+', assuming positivity if neither is present.
3. Conversion: read the next characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Rounding: if the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -2^31 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1.
Return the integer as the final result.
Constraints
0 <= s.length <= 200sconsists of English letters (lower-case and upper-case), digits (0-9),' ','+','-', and'.'
Examples
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization