String to Integer (atoi)
Medium · strings
A form field gives you text, and you need to read a whole number from the start of it. Given a string s, work through these steps and return the number you end up with.
- Skip any spaces at the start of
s. Only the space character counts as a space. - If the next character is
-or+, remember the sign and move past it. With no sign the number is positive. - Read digits one after another and stop at the first character that is not a digit (or at the end of the string). Ignore everything after that point.
- Leading zeros are allowed. If you read no digits at all, the answer is
0. - Apply the sign. If the result is below
-2^31, return-2^31. If it is above2^31 - 1, return2^31 - 1.
Only the start of the string matters: " -12abc" gives -12, but "abc 12" gives 0 because the first thing after the spaces is not a sign or a digit.
Examples
Example 1
Input: s = " -42"
Output: -42
The spaces are skipped, the sign is negative and the digits are 4 and 2.
Example 2
Input: s = "4193 with words"
Output: 4193
Reading stops at the space after 4193.
Example 3
Input: s = "-91283472332"
Output: -2147483648
The number is below the lowest 32-bit value, so it is clamped to -2^31.
Example 4
Input: s = "words and 987"
Output: 0
The first character is a letter, so no digits are read.
Constraints
- 0 <= len(s) <= 10^5
- s contains English letters, digits, ' ', '+', '-' and '.'.