String to Integer (atoi)
MediumString · NVIDIA
Convert the beginning of the string s into a 32-bit signed integer by applying these steps in order:
- Spaces: skip any leading space characters (
' '). Only the space character counts as whitespace. - Sign: if the next character is
'+'or'-', read it as the sign. At most one sign character is read; with no sign the number is positive. - Digits: read consecutive digits until you reach a non-digit character or the end of the string. Leading zeros are allowed and add nothing. Everything after the digits is ignored.
- No digits: if step 3 read no digits, return
0. - Clamp: apply the sign. If the result is below
-2^31(-2147483648), return-2147483648; if it is above2^31 - 1(2147483647), return2147483647.
Any other character met before the digits (a letter, a ., a second sign, or a space after the sign) stops parsing at that point.
Example 1
- Input:
- s = " -0072 apples"
- Output:
- -72
- Explanation
- Skip the three spaces, read
-as the sign, then read the digits0072and stop at the space. The leading zeros add nothing, so the value is-72.
Example 2
- Input:
- s = "+-12"
- Output:
- 0
- Explanation
- After the
+sign the next character is-, which is not a digit, so no digits are read and the answer is0.
Example 3
- Input:
- s = "9876543210xyz"
- Output:
- 2147483647
- Explanation
- The digits form 9876543210, which is larger than
2147483647, so the result is clamped to2147483647.
Constraints
0 <= s.length <= 200sconsists of English letters, digits,' ','+','-', and'.'