String to Integer (atoi)
Implement myAtoi, which converts a string to a 32-bit signed integer. Skip leading spaces, read an optional single '+' or '-' sign, then read consecutive digits, stopping at the first non-digit. Ignore everything after the number. If no digits were read, return 0. Clamp the result to the 32-bit signed range [-2^31, 2^31 - 1].
Open official problem prompt ↗Turn the leading numeric prefix of a possibly-messy string into a bounded 32-bit integer, following a fixed set of parsing rules.
Like a turnstile that only lets certain tokens through in order: first ignore the queue of blanks, admit one sign token, then let a run of digits pass, and slam the gate the moment something unexpected arrives.
- Input
- s = " -42"
- Output
- -42
- Why
- Three leading spaces are skipped, '-' sets the sign, then '42' is read as digits, giving -42.
0 <= s.length <= 200s consists of English letters (lower/upper), digits, ' ', '+', '-', and '.'