String to Integer with Clamping
Problem statement
Skip leading ASCII spaces, then consume at most one optional + or - sign followed immediately by a maximal run of decimal digits. Stop at the first other character and ignore the remaining suffix. Return 0 if no digit was consumed. Clamp results to the signed 32-bit interval [-2147483648,2147483647]. Only the ordinary space character is skipped; interior spaces end digit parsing.
Function
parseInteger(s: String) → intExamples
Example 1
s = " -42words"return = -42Two leading spaces are skipped, the sign is negative, and the digit run is 42 before w.
Example 2
s = "2147483648"return = 2147483647The positive value exceeds the upper signed32 limit and is clamped to 2147483647.
Constraints
0 <= s.length <= 1000.- Every character is printable ASCII with a code from 32 through 126.