An old form reader turns whatever people typed into a 32-bit integer. It never rejects input: it reads as much of a number as it can find at the start and ignores the rest.
Write string_to_int(s: str) -> int that follows these rules, in order:
- Skip leading space characters
' '. Only spaces are skipped; any other character ends this step. - If the next character is
'+'or'-', read it as the sign. At most one sign is allowed. With no sign the number is positive. - Read digits
0-9until the first character that isn't a digit, or the end of the string. Leading zeros are fine. Everything after the digits is ignored. - If step 3 read no digits at all, the answer is
0. - If the number is outside the 32-bit range
[-2^31, 2^31 - 1], clamp it: anything below-2147483648becomes-2147483648, and anything above2147483647becomes2147483647.
string_to_int(" -0042 apples") # -42 (spaces, sign, digits; " apples" is ignored)
string_to_int("+17") # 17
string_to_int("3.99") # 3 (the "." stops the digits)
string_to_int("about 12") # 0 ("a" is not a space, sign or digit)
string_to_int("-+5") # 0 (a second sign is not a digit)
string_to_int(" - 5") # 0 (no digits right after the sign)
string_to_int("98765432109") # 2147483647 (too big, clamped)
string_to_int("-2147483649") # -2147483648 (too small, clamped)
Constraints: 0 <= len(s) <= 200; s holds English letters, digits, spaces, '+', '-' and '.'.
In C++ and Java, the digits can run far past what even a 64-bit integer holds, so stop growing the number once it is out of range.
Show hint
walk an index through the string, one step per rule. Before adding each digit, check whether the result is already past the limit.