MediumStringsMath

1 approach, code in every language

Problem description

Convert a string into a signed 32-bit integer by scanning it the way a hand-written parser would. First skip any leading spaces, then read an optional single plus or minus sign, then collect the run of decimal digits that follows. Reading stops at the first character that is not a digit, and everything after that point is ignored.

If no digits appear the result is 0. When the assembled number falls outside the signed 32-bit range, clamp it: values below the minimum become -2^31 and values above the maximum become 2^31 - 1.

Example 1

Input: s = " -042"

Output: -42

Leading spaces are skipped, the minus sign is recorded, and the leading zero in 042 is absorbed to give -42.

Example 2

Input: s = "4193 with words"

Output: 4193

Digits are gathered until the space, so the trailing text is discarded.

Constraints

  • 0 <= s.length <= 200
  • s consists of spaces, digits, letters, '+', '-', and '.'
  • The final value is clamped to the range [-2^31, 2^31 - 1]

After the pattern

Now solve one you haven't seen.

Salvage the Leading Number is our own problem on the technique behind String to Integer (atoi): a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free