
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive Implementation of Atoi in C++
We are given a string containing a number. The goal is to find the equivalent number using the recursive atoi() method. int atoi(const char *str) converts the string argument str to an integer (type int).
Example-:
Input − Str[] = "58325"
Output − The Equivalent decimal is :58325
Explanation − The string contains the equivalent number 58325
Input − Str[] = "00010"
Output − The Equivalent decimal is :1
Explanation − The string contains the equivalent number 10.
Approach used in the below program is as follows
In this approach we are using the recursive function recurAtoi() which takes input string and its length and for each character convert it to decimal and multiply it with 10. Add previous results to it.
Take the input string Str[] containing a number.
Calculate its length using strlen(Str).
Function recurAtoi(char *str, int len) takes input and returns the number calculated using recursive atoi() functionality.
If length is 1 return digit *str -’0’.
Take temp=10*recurAtoi(str,len-1).
And set temp=temp+str[len-1]-'0'.
At the end return temp.
Print result.
Example
#include <bits/stdc++.h> using namespace std; int recurAtoi(char *str, int len){ if (len == 1){ return *str - '0'; } int temp=10*recurAtoi(str,len-1); temp=temp+str[len-1]-'0'; return (temp); } int main(void){ char Str[] = "58325"; int length = strlen(Str); cout<<"Equivalent decimal :"<<recurAtoi(Str, length); return 0; }
Output
If we run the above code it will generate the following Output
Equivalent decimal : 58325