Skip to main content
Back to problems
Leetcode
Medium
Strings
Simulation
Math
String to Integer (atoi)

Convert a string to a 32-bit signed integer, following atoi parsing rules for whitespace, sign, digits, and overflow clamping.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

atoi

gfg
Problem Statement

Given a string s, interpret it as a 32-bit signed integer using rules similar to the classic atoi function.

Parse the string from left to right and build the integer result under these rules:

  1. Ignore any leading whitespace.
  2. Read at most one optional sign character: + or -.
  3. Read digits consecutively until the first non-digit character is reached.
  4. If no digits are read, the result is 0.
  5. If the parsed value exceeds the 32-bit signed integer range, clamp it to the nearest bound.

Return the final integer value.

Input Format

  • A single string s.

The string may contain leading spaces, an optional sign, digits, and other trailing characters.

Output Format

  • Return a single integer representing the parsed and clamped value.

Constraints

  • The result must fit within the signed 32-bit integer range: [$-2^{31}$, $2^{31}-1$].
  • Parsing stops at the first character that is not a digit after optional leading spaces and sign.
  • If no valid numeric prefix exists, return 0.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "42"

Output

42

Explanation

The string starts with digits, so the parsed integer is 42.

Example 2

Input

s = "   -42"

Output

-42

Explanation

Leading spaces are ignored, then the negative sign is applied to the parsed digits.

Show 3 more examples

Example 3

Input

s = "4193 with words"

Output

4193

Explanation

Parsing stops when a non-digit character is encountered after reading digits.

Example 4

Input

s = "words and 987"

Output

0

Explanation

No valid numeric prefix starts at the beginning after skipping leading whitespace.

Example 5

Input

s = "-91283472332"

Output

-2147483648

Explanation

The value is smaller than the 32-bit signed minimum, so it is clamped.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.