InferenceAI

Enter at least two characters to search.

Start free

Parse an Integer

mediumArrays & Strings25 min25 XP

Convert a string to a 32-bit signed integer:

  1. Skip leading spaces.
  2. Read an optional + or - sign.
  3. Read digits until a non-digit or the end.
  4. Clamp the result to [−231,231−1][-2^{31}, 2^{31} - 1].

If no digits are read, return 0.

Examples

EXAMPLE WALKTHROUGHplain

A guided view of the published example, not a trace of your code.

INPUT["42"]
TASKparse_integer()
EXPECTED OUTPUT42

Start with the input values shown in this example.

Example 1 of 3

Input: s = "42"

Output: 42

Explanation: plain

Input: s = " -42"

Output: -42

Explanation: spaces and sign

Input: s = "4193 with words"

Output: 4193

Explanation: stops at text

Hint 1

Walk an index through the string step by step.

Hint 2

Clamp at the end (Python integers don't overflow), but think about how you'd check overflow in C++ or Java.

Topics

DSAArrays & StringsPython