AlgoViz

Recursive Implementation of atoi()

Medium

Build the number from the front

Problem

Convert a numeric string to its integer value using recursion (implement atoi).

In simple words

Read a sign then digits, building the number as recursion walks the string.

The idea

Handle the sign and leading spaces, then consume digits one at a time with result = result * 10 + digit, recursing on the rest of the string. Stopping at the first non-digit is what makes it match the real atoi.

The trick

  • Multiply by 10 before adding the new digit.
  • Clamp to the 32-bit range rather than letting it overflow.
  • Stop at the first character that is not a digit.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

234
0

Step 1 of 2. Here's the example — '234' Values: 234.

1/2
Optimal
timeO(n)spaceO(n)
1f(s):2  if len(s)==1: return s[0]-'0'3  return f(s[:-1])*10 + (s[-1]-'0')

Input

array
[234]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
s = "42"
Output:
42
Explanation:
Straightforward: 42.

Example 2

Input:
s = " -42"
Output:
-42
Explanation:
Skip spaces, honour the minus → -42.

Example 3

Input:
s = "4193 with words"
Output:
4193
Explanation:
Read digits until letters stop it → 4193.

Finished the walkthrough? Add it to your streak.