Home » Interview Questions » String Interview Questions » Recursive Implementation of atoi()

Recursive Implementation of atoi()


()

atoi() function takes an string(which is a number) as an argument and returns its value

Example

INPUT
s = “33”

OUTPUT
33

In the above example, we are passing 33 as a string and the output is a value

Algorithm

1. Separate the last digit and recursivley compute result for remaining n-1 digits
a. Multiply the result with 10 and add the obtained value to last digit

C++ Program

// Recursive C++ program to compute atoi()
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to compute atoi()
int atoiRecursively(char *s, int n)
{
    // Base case (Only one digit)
    if (n == 1)
        return *s - '0';
 
    // If more than 1 digits, recur for (n-1), multiply result with 10
    // and add last digit
    return (10 * atoiRecursively(s, n - 1) + s[n-1] - '0');
}
 
// Driver Program
int main(void)
{
    char s[] = "33";
    int n = strlen(s);
    cout<<atoiRecursively(s, n)<<endl;
    return 0;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Valid Number
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions