dsa · medium

String to Integer

Parse a signed 32-bit integer out of s.

Arguments

Skip every leading space. Then an optional + or -. Then read the longest run of digits. Stop at the first character that is not a digit (or at the end). If that run is empty, the value is 0. Clamp the signed result into [-2^31, 2^31 - 1] — too large becomes 2^31 - 1, too small becomes -2^31.

Example

s = "42" has no spaces or sign, so the digits are 4242.

s = " -42" skips three spaces, takes the minus, then 42-42.

s = "4193 with words" reads 4193 and stops at the space → 4193.

s = "words and 987" has no leading sign or digit, so the run is empty → 0.

Constraints

1 <= s.length <= 200 s may contain letters, digits, spaces, "+", "-", and "." Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
"42"

Expected:
42

Example 2

Input:
"   -42"

Expected:
-42

Example 3

Input:
"4193 with words"

Expected:
4193

Open in the Dojo editor