← DiffPush

Implement atoi via recursion

Baseline Recursion · Get Strong Hold O(n) · O(n) recursion stack

The Legacy Meter's Recursive Decoder

A field sensor from an older product line transmits its reading as a raw digit string, and the new firmware's parser must reproduce the legacy decoder exactly. The decoder walks the string from its right end, folding each digit into the running value one position at a time, and refuses the whole transmission the moment any character is not a digit. A single leading minus flips the result negative.

Input: A string str of ASCII characters, optionally starting with '-'.

Output: The integer value of str when every character (after an optional leading '-') is a digit; otherwise -1.

Constraints

Examples

Example 1

Input: {"str":"123"}
Output: 123
Three digits fold left from the right: 3, then 23, then 123.

Example 2

Input: {"str":"21a"}
Output: -1
The trailing letter fails the digit check, so the entire reading is rejected.

Solve this in your browser →

Also on LeetCode ↗