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