String to Integer (atoi) - Problem

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer following these rules:

  1. Whitespace: Ignore any leading whitespace characters
  2. Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present
  3. 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
  4. 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
String to Integer (atoi) ProcessInput String" -42abc"Step 1:Skip Spaces" "Step 2:Parse Sign"-"Step 3:Convert Digits"42"Final Result-42
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
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
89.2K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen