DSA Tracker

Visualize

String to Integer (atoi)

Skip spaces, read sign, consume digits, stop at the first non-digit

time O(n)space O(1)

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

[0]
[1]
[2]
-
[3]
4
[4]
2
[5]

s=" -42". Parse left to right: skip leading whitespace, read an optional sign, then consume digits until a non-digit or the end.

Pseudocode
1FUNCTION myAtoi(s):
2 skip any leading spaces
3 sign = 1; if s[i] is '+' or '-': set sign accordingly and move i one step right
4 num = 0
5 WHILE s[i] is a digit:
6 num = num*10 + the digit; move i one step right
7 RETURN sign * num

← / → step · space play · Home restart

Every step in words

Show all 6 steps
  1. s=" -42". Parse left to right: skip leading whitespace, read an optional sign, then consume digits until a non-digit or the end.
  2. Skip 3 leading spaces. i=3.
  3. Sign character '-' found -> sign=-1.
  4. digit '4': num = num*10 + 4 = 4.
  5. digit '2': num = num*10 + 2 = 42.
  6. 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.