Home  >  Article  >  Backend Development  >  Implement atoi() function recursively in C++

Implement atoi() function recursively in C++

PHPz
PHPzforward
2023-08-27 13:57:09768browse

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).

Example:

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.

The method used in the following program is as follows

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.

Example

#include <bits/stdc++.h>
using namespace std;
int recurAtoi(char *str, int len){
   if (len == 1){
      return *str - &#39;0&#39;;
   }
   int temp=10*recurAtoi(str,len-1);
   temp=temp+str[len-1]-&#39;0&#39;;
   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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete