String to Integer (atoi)
Parse a string into a 32-bit integer the way C's atoi does: skip spaces, optional sign, digits until a non-digit, clamp to [−2³¹, 2³¹−1].
Intuition
This is a tiny state machine: whitespace → sign → digits → stop. The only real trap is overflow — clamp when the accumulating value crosses the 32-bit boundary, checking before it grows out of range in fixed-width languages.
Approach
Three phases in order
Skip leading spaces only; read at most one sign; consume digits until the first non-digit ends parsing. Anything malformed before a digit → 0.
Accumulate and clamp
num = num*10 + digit. If it exceeds 2³¹−1, return the clamp (positive) or −2³¹ (negative). Python can check after; C/Java must check before multiplying.
Everything else is ignored
Trailing garbage after digits is fine — parsing simply stops.
Solution & live demo
Edge cases
Spaces skipped, sign captured → −42.
First: parses 4193 then stops. Second: no leading digit → 0.
Below INT_MIN → clamps to −2147483648.