Strings Parsing and conversion

139. Implement atoi with Recursion

Medium

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"

Output: -309

Explanation: The - makes the number negative, and the zeros at the front add nothing, so the answer is −309.

Example 2

Input: s = "+2147483648"

Output: 2147483647

Explanation: 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"

Output: 0

Check your understanding

Work out the answer for this input before you write any code.

s = "-9999999999"

Constraints

  • 1 ≤ s.length ≤ 1000
  • s[0] is '+', '-' or a digit, and every other character of s is a digit
  • s holds at least one digit

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.