String to Integer (atoi)
MediumP2Coding
Implement myAtoi(s), which converts a string to a 32-bit signed integer. Follow these steps:
- Skip leading spaces (only the space character).
- If the next character is
+or-, read it as the sign. Without a sign the number is positive. - Read digits until a non-digit or the end of the string. Ignore everything after.
- If no digits were read, the result is 0.
- If the value is outside the 32-bit signed range [-2^31, 2^31 - 1], clamp it to the nearest bound.
Example 1
- Input
- s = "42"
- Output
- 42
Example 2
- Input
- s = " -42"
- Output
- -42
Example 3
- Input
- s = "4193 with words"
- Output
- 4193
Constraints
- 0 <= s.length <= 200
- s consists of letters, digits, spaces, '+', '-' and '.'.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 16. ⌘Enter runs, ⌘⇧Enter submits.