Home >Backend Development >C++ >Implement atoi() function recursively in C++
We get a string containing numbers. The goal is to find equivalent numbers using the recursive atoi() method. int atoi(const char *str) Converts the string argument str to an integer (type int).
Input− Str[] = "58325"
Output− The equivalent decimal is: 58325
Explanation− The string contains the equivalent number 58325
Input− Str[] = "00010"
Output− The decimal equivalent is: 1
Explanation - The string contains the equivalent number 10.
In this method, we use the recursive function recurAtoi() to get the input string and its length and convert it to decimal for each character and multiply by 10. Add the previous results to it.
Get the input string Str[] containing numbers.
Use strlen(Str) to calculate its length.
The function recurAtoi(char *str, int len) accepts input and returns a number calculated using the recursive atoi() function.
If the length is 1, the number *str -'0' is returned.
Take temp=10*recurAtoi(str,len-1).
And set temp=temp str[len-1]-'0'.
Finally returns the temperature.
Print the results.
#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; }
If we run the above code it will generate the following output
Equivalent decimal : 58325
The above is the detailed content of Implement atoi() function recursively in C++. For more information, please follow other related articles on the PHP Chinese website!