Problem Statement
String to Integer (atoi)
We need to write a function called myAtoi that turns a piece of text into a whole number. For example, the text "42" should become the number 42. The rules are: first, skip any spaces at the front. Then, look for a plus or minus sign that tells us if the number is positive or negative. Then, read digits one at a time until we hit something that is not a digit, or until the text ends. Finally, keep the answer inside the range a 32-bit signed integer can hold, which is from -2,147,483,648 up to 2,147,483,647. A "32-bit signed integer" just means a number stored in a fixed amount of computer memory, so it has a smallest and a largest value it can be. If our number goes past either end, we squeeze it back to the nearest allowed value. This is called clamping. The math here is easy. The hard part is handling the tricky cases carefully: empty text, text with no digits at all, extra spaces, and numbers so big they spill past the limit.
Signals to notice
Brute force first
Not applicable — parsing IS the task.
The key insight
Sequential: skip whitespace → read sign → read digits → clamp to INT range. O(n).
Trace it on s=" -42"
init: i=0, n=6, result=0, sign=1 skip whitespace: s[0..2]==' ', i advances to 3 (s[3]=='-') i != n, so not empty -> continue read sign: s[3]=='-', set sign=-1, i=4 digit loop, s[4]=='4': overflow check 0 > (2147483647-4)//10? no; result=0*10+4=4, i=5 digit loop, s[5]=='2': overflow check 4 > (2147483647-2)//10? no; result=4*10+2=42, i=6 i==n, loop ends; return sign*result = -1*42 = -42
What must stay true
Process one concern at a time. Check overflow BEFORE multiplying: if result > INT_MAX/10, clamp.
Shape of the loop
i = skip leading spaces in s
sign = read optional '+'/'-' at i, advance i
result = 0
while i < len(s) and s[i] is a digit:
if result > (INT_MAX - digit) // 10: return clamped INT_MAX/INT_MIN
result = result*10 + digit; i += 1
return sign * resultPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Overflow during digit accumulation — check before result = result * 10 + digit, not after.