Skip to content

Practice String to Integer (atoi)

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#8
LeetCode Problem

String to Integer (atoi)

Problem Statement

Implement myAtoi(s) manually, without a built-in string-to-number conversion. Skip leading spaces, read at most one optional sign, then read consecutive decimal digits until another character or the end. Return zero if no digit was read. Clamp the result to the signed 32-bit range [-2^31, 2^31 - 1]. Practice approach: Scan once with a sign and numeric accumulator. Before multiplying by ten and adding a digit, check whether that step would exceed the sign-specific limit; clamp when it would. A sign after digit parsing begins ends the number. Time is O(n) with O(1) extra space. Test an empty string, an isolated sign, trailing letters, and both overflow directions.

Source: String to Integer (atoi) on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
s = "   -17tail"
Output
-17
Explanation

Spaces are skipped, the minus sign is accepted, and reading stops at t.

# Example 2

Input
s = "2147483648"
Output
2147483647
Explanation

The positive value exceeds the signed 32-bit upper limit and is clamped.

# Example 3

Input
s = "+-8"
Output
0
Explanation

After one sign, the next character is not a digit; no number is read.

Constraints

0 <= s.length <= 200
s contains English letters, decimal digits, spaces, '+', '-', and '.'.

Related LeetCode Problems

Practice more problems similar to String to Integer (atoi).

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.