0008. String to Integer (atoi)

Algorithm for converting a string to a 32-bit signed integer

Step-by-step Parsing
State Machine (DFA)
Regex
Examples:
"42"
" -42"
"4193 with words"
"words and 987"
"-91283472332"
"+1"
" + 42"
""
Speed: 5x
Active
Whitespace
Sign
Digit
Ignored
Overflow
Index (i)
0
Phase
Ready
Sign
+1
Result
0
Final

Step-by-step log:

Algorithm Complexity
Single Pass
O(n)
O(n) / O(1)
Examples:
"42"
" -42"
"4193 with words"
"words and 987"
"-91283472332"
Speed: 5x
' ' +/- 0-9 other 0-9 other 0-9 other q0 start q1 signed q2 number qd end
Current State
q0 (start)
Character
Sign
+1
Result
0

DFA Transitions:

Examples:
"42"
" -42"
"4193 with words"
"words and 987"
"-91283472332"
Regex Pattern:
^\s*([+-]?\d+)
Match
Parsed Integer
Clamped

Regex process: