String to Integer (atoi) - Problem
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer following these rules:
- Whitespace: Ignore any leading whitespace characters
- Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present
- Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0
- Rounding: If the integer is out of the 32-bit signed integer range [-2³¹, 2³¹ - 1], then clamp the integer to remain in the range
Return the integer as the final result.
Input & Output
Example 1 — Basic Negative Number
$
Input:
s = "42"
›
Output:
42
💡 Note:
Simple case: skip no whitespace, no sign, convert digits "42" to integer 42
Example 2 — Whitespace and Sign
$
Input:
s = " -42"
›
Output:
-42
💡 Note:
Skip leading spaces, parse negative sign, convert "42" and apply sign to get -42
Example 3 — Mixed Characters
$
Input:
s = "4193 with words"
›
Output:
4193
💡 Note:
Convert "4193" until space character encountered, ignore remaining characters
Constraints
- 0 ≤ s.length ≤ 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with potential whitespace, sign, digits, and other chars
2
Process
Parse systematically: skip whitespace → check sign → convert digits
3
Output
32-bit signed integer with overflow clamping
Key Takeaway
🎯 Key Insight: Handle parsing systematically with proper overflow detection using mathematical bounds
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code