String to Integer (atoi)
Problem statement
Convert s to a signed 32-bit integer.
- Skip leading ASCII space characters.
- Read one optional
+or-sign. - Consume the longest following prefix of decimal digits. If no digit is consumed, return
0. - Ignore every character after that digit prefix.
- Clamp a value below
-2^31to-2^31and a value above2^31 - 1to2^31 - 1.
Function
stringToInteger(s: String) → intExamples
Example 1
s = "123"return = 123All characters belong to the decimal digit prefix.
Example 2
s = " -042xyz"return = -42Leading spaces and the negative sign are consumed. Parsing stops before x.
Example 3
s = "91283472332"return = 2147483647The parsed positive value exceeds the signed 32-bit maximum and is clamped.
Constraints
0 <= s.length <= 200.smay contain ASCII letters, digits, spaces, signs, and punctuation.