String to Integer (atoi) - Problem
Ever wondered how programming languages convert strings to integers? Welcome to the world of atoi (ASCII to Integer)! Your mission is to implement a string-to-integer conversion function that mimics the behavior of C's atoi function.
Given a string s, your function myAtoi(s) should convert it to a 32-bit signed integer following these rules:
- Skip Whitespace: Ignore any leading whitespace characters (
' ') - Handle Sign: Check if the next character is
'-'or'+'. If neither is present, assume positive. - Convert Digits: Read digits until you encounter a non-digit character or reach the end. Skip leading zeros.
- Handle Empty: If no digits were read, return 0.
- Clamp Range: If the result exceeds the 32-bit signed integer range
[-2³¹, 2³¹ - 1], clamp it to the boundary values.
Challenge: Handle edge cases like overflow, underflow, and invalid characters gracefully!
Input & Output
example_1.py — Basic Conversion
$
Input:
s = "42"
›
Output:
42
💡 Note:
Simple numeric string converts directly to integer 42
example_2.py — Whitespace and Sign
$
Input:
s = " -42"
›
Output:
-42
💡 Note:
Leading whitespace is ignored, negative sign is processed, resulting in -42
example_3.py — Mixed Characters
$
Input:
s = "4193 with words"
›
Output:
4193
💡 Note:
Digits are read until the first non-digit character (space), so only '4193' is converted
example_4.py — Overflow Case
$
Input:
s = "91283472332"
›
Output:
2147483647
💡 Note:
Number exceeds 32-bit integer maximum, so it's clamped to 2³¹-1 = 2147483647
Visualization
Tap to expand
Understanding the Visualization
1
Initialize State
Start with result = 0, sign = 1, and begin scanning
2
Skip Whitespace
Ignore leading spaces until we find a non-space character
3
Process Sign
If we see '+' or '-', record the sign and move to next character
4
Build Number
For each digit, multiply current result by 10 and add the digit
5
Check Overflow
Before each multiplication, verify we won't exceed 32-bit limits
6
Return Result
Apply sign and return the final clamped result
Key Takeaway
🎯 Key Insight: The optimal solution is essentially a finite state machine that processes each character exactly once, making decisions based on the current state and input character. This eliminates the need for multiple passes or string manipulation.
Time & Space Complexity
Time Complexity
O(n)
Although we make multiple passes, each is O(n), so overall still O(n)
✓ Linear Growth
Space Complexity
O(n)
Creates intermediate strings for processing
⚡ Linearithmic Space
Constraints
- 0 ≤ s.length ≤ 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'
- Follow-up: Can you solve it without using any built-in library functions for string-to-integer conversion?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code