8/670

8. String to Integer (atoi)

Medium

You are given a single string s. Convert it to a 32-bit signed integer using the classic atoi-style rules, scanning left to right:

  1. Skip any leading space characters.
  2. Read an optional single sign, '+' or '-'. If neither is present, the number is positive.
  3. Read the consecutive digits that follow, forming the integer. Stop as soon as you hit a character that is not a digit (or reach the end of the string). Any remaining characters are ignored.
  4. If no digits were read at all, the result is 0.

Finally, clamp the value to the signed 32-bit range. If it is below -2^31 (-2147483648), return -2147483648, if it is above 2^31 - 1 (2147483647), return 2147483647, otherwise return the value as read.

Return the resulting integer. Only leading spaces are skipped, a space that appears between the sign and the digits, or before the first digit after other characters, ends the number.

Example 1:

Input: s = "42"

Output: 42

Explanation: No leading spaces or sign. The digits "42" are read to the end, giving 42, which is already in range.

Example 2:

Input: s = " -042"

Output: -42

Explanation: Skip the three leading spaces, read the '-' sign, then the digits "042" (leading zeros are harmless). The value is -42.

Example 3:

Input: s = "words and 987"

Output: 0

Explanation: The first non-space character is 'w', which is neither a sign nor a digit, so digit reading stops immediately with nothing read. The result is 0.

Constraints:

  • 0 ≤ s.length ≤ 200
  • s consists of English letters (upper and lower case), digits (0-9), ' ', '+', '-', and '.'.
  • The answer is clamped to the signed 32-bit range [-2³¹, 2³¹ - 1].

Hints:

Keep a single index and move through four ordered phases: skip spaces, read one optional sign, read consecutive digits, then clamp.

Only the first run of leading spaces is skipped. A space after the sign (" + 413") or a sign followed by a non-digit ("+-12") means no digits are read, so the answer is 0.

Beware overflow: either accumulate in a 64-bit integer and clamp, or check `result > (INT_MAX - digit) / 10` before multiplying so you never overflow a 32-bit int.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "42"

Expected output: 42