ExamAdda Logo

String to Integer (atoi)

Easy

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

1. Ignore any leading whitespace.
2. Check if the next character is '-' or '+'. Assume the result is positive if neither is present.
3. Read the digits until a non-digit character is encountered or the end of the string is reached.
4. Convert the digits into an integer.
5. If the integer is outside the 32-bit signed integer range [-2³¹, 2³¹ - 1], clamp it to the nearest limit.

Return the resulting integer.

Example 1

Input

42

Output

42

Explanation

The string contains only digits, so the converted integer is 42.

Example 2

Input

-42

Output

-42

Explanation

Leading spaces are ignored, then the negative sign is processed before reading the digits.

Constraints

0 ≤ s.length ≤ 200
s consists of English letters
digits
spaces
'+'
'-'
and '.'.

Hints:

Hint 1

Skip all leading whitespace characters before processing the string.

Hint 2

Handle the optional sign, read consecutive digits, and check for integer overflow before updating the result.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 5, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output