String to Integer (atoi)
Problem statement
Convert the leading decimal integer in the ASCII string text into a signed 32-bit integer.
- Skip leading ASCII whitespace: space, tab, line feed, vertical tab, form feed, or carriage return.
- Read at most one optional
+or-sign. - Read the immediately following consecutive digits. Stop at the first nondigit; ignore the remaining suffix.
- Return zero if no digits were read. Clamp a value outside
[-2147483648,2147483647]to the nearest endpoint.
Only the leading digit run is parsed; decimal points, exponents, and later digit runs are not special syntax.
Function
parseAtoi(text: String) → intExamples
Example 1
text = " -42tail"return = -42Skip spaces, read the minus sign and digits 42, and stop before the suffix.
Example 2
text = "4193 with words"return = 4193Parsing stops at the first space after the digits.
Example 3
text = "words 987"return = 0The leading non-whitespace character is not a sign or digit.
Constraints
0 <= text.length <= 2000.- Every input character is ASCII.