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.
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
s = " -17tail"
-17
Spaces are skipped, the minus sign is accepted, and reading stops at t.
# Example 2
s = "2147483648"
2147483647
The positive value exceeds the signed 32-bit upper limit and is clamped.
# Example 3
s = "+-8"
0
After one sign, the next character is not a digit; no number is read.
Constraints
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.