Recursive Implementation of atoi()
MediumBuild the number from the front
Problem
Convert a numeric string to its integer value using recursion (implement atoi).
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.
Step 1 of 2. Here's the example — '234' Values: 234.
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.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.