Visualize

Pattern visualizer

String to Integer (atoi)

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. 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..

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

time O(n)space O(1)step 1 / 6
[0]
[1]
[2]
-
[3]
4
[4]
2
[5]
line 2

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

Where to practice Strings