String to Integer (atoi)
Skip spaces, read sign, consume digits, stop at the first non-digit
This problem is really just careful sequencing: whitespace can only appear at the very front, a sign (if any) can only appear once right after that, and digits are consumed greedily until the string runs out or hits something that isn't a digit — at which point parsing stops immediately, even if characters remain. No character is ever revisited.
Details
Animated on: s = " -42" — convert to a 32-bit signed integer the way a real atoi does: skip leading whitespace, then parse as much as forms a valid number.
Problem:String to Integer (atoi)Medium
Skip spaces, read sign, consume digits, stop at the first non-digit
step 1 / 6
s=" -42". Parse left to right: skip leading whitespace, read an optional sign, then consume digits until a non-digit or the end.
1FUNCTION myAtoi(s):2 skip any leading spaces3 sign = 1; if s[i] is '+' or '-': set sign accordingly and move i one step right4 num = 05 WHILE s[i] is a digit:6 num = num*10 + the digit; move i one step right7 RETURN sign * num
← / → step · space play · Home restart
Every step in words
Show all 6 steps
- s=" -42". Parse left to right: skip leading whitespace, read an optional sign, then consume digits until a non-digit or the end.
- Skip 3 leading spaces. i=3.
- Sign character '-' found -> sign=-1.
- digit '4': num = num*10 + 4 = 4.
- digit '2': num = num*10 + 2 = 42.
- Digits end at i=6 (end of string). Apply the sign: -1 * 42 = -42.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.