Strings Parsing and conversion
139. Implement atoi with Recursion
You are given a string s that holds a whole number: an optional sign, + or -, followed by one or more
digits. Return the number as a signed 32-bit integer. Write the solution with recursion, without a loop.
Zeros at the front of the number add nothing to it. A signed 32-bit integer holds the values from −231 to 231 − 1, that is from −2,147,483,648 to 2,147,483,647. If the number is larger than 2,147,483,647, return 2,147,483,647. If it is smaller than −2,147,483,648, return −2,147,483,648.
As in String to Integer (atoi), use 32-bit integers only. No value in your code should go outside that range, even for a moment.
Example 1
Input: s = "-00309"
-309Explanation: The - makes the number negative, and the zeros at the front add nothing, so the answer is −309.
Example 2
Input: s = "+2147483648"
2147483647Explanation: 2,147,483,648 is 1 more than the largest 32-bit value, so the answer is 2,147,483,647.
Example 3
Input: s = "0"
0Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 1000s[0]is'+','-'or a digit, and every other character ofsis a digitsholds at least one digit
Clarifying questions
What you would ask an interviewer before writing any code.