The atoi() function takes a string (which represents an integer) as an argument and returns its value. We have discussed iterative implementation of atoi(). How to compute recursively?
Approach:
The idea is to separate the last digit, recursively compute the result for the remaining n-1 digits, multiply the result by 10 and add the obtained value to the last digit.
Below is the implementation of the idea.
C++
#include <cctype>
#include <cstring>
#include <iostream>
using namespace std;
int myAtoiRecursive(char* str, int n)
{
int count = 0, check;
for (int i = 0; i <= strlen(str); ++i) {
check = isalpha(str[i]);
if (check)
++count;
}
if (count != 0) {
return 0;
}
if (n == 1)
return *str - '0';
return (10 * myAtoiRecursive(str, n - 1) + str[n - 1]
- '0');
}
int main(void)
{
char str[] = "112";
int n = strlen(str);
printf("%d", myAtoiRecursive(str, n));
return 0;
}
|
Java
class GFG{
static int myAtoiRecursive(String str, int n)
{
if (str == "" || !str.matches("^\\d*$")) {
return 0;
}
if (n == 1)
{
return str.charAt(0) - '0';
}
return (10 * myAtoiRecursive(str, n - 1) +
str.charAt(n - 1) - '0');
}
public static void main(String[] s)
{
String str = "112";
int n = str.length();
System.out.println(myAtoiRecursive(str, n));
}
}
|
Python3
def myAtoiRecursive(string, num):
if string.isalpha() :
return 0;
if(len(string) == 0):
return 0;
if len(string) == 1:
return int(string) + (num * 10)
num = int(string[0:1]) + (num * 10)
return myAtoiRecursive(string[1:], num)
string = "112"
print(myAtoiRecursive(string, 0))
|
C#
using System;
using System.Text.RegularExpressions;
class GFG{
static int myAtoiRecursive(string str, int n)
{
if (Regex.IsMatch(str, "^[a-zA-Z]*$")){
return 0;
}
if (n == 1)
{
return str[0] - '0';
}
return (10 * myAtoiRecursive(str, n - 1) +
str[n - 1] - '0');
}
public static void Main()
{
string str = "112";
int n = str.Length;
Console.Write(myAtoiRecursive(str, n));
}
}
|
Javascript
<script>
function myAtoiRecursive(str, n)
{
if (str.match(/^[A-Za-z]+$/)) {
return 0;
}
if (n == 1)
{
return str[0].charCodeAt() - '0'.charCodeAt();
}
return (10 * myAtoiRecursive(str, n - 1) + str[n - 1].charCodeAt() - '0'.charCodeAt());
}
let str = "112";
let n = str.length;
document.write(myAtoiRecursive(str, n));
</script>
|
Time complexity: O(n),
Auxiliary Space: O(n)
Last Updated :
19 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...