Home > OS >  Write a recursive function to convert a given string into the number it represents
Write a recursive function to convert a given string into the number it represents

Time:07-02

In this code, I want to convert the string into integer by using recursive function but it is giving output in negetive.

#include <iostream>

using namespace std;

int convert1(string s) {
    if (s.length() == 1) {
        int i = s[0] - '0';
        return i;
    }

    int so = convert1(s.substr(0, s.length() - 1));
    int num = s[s.length()] - '0';
    int ans = so * 10   num;
    return (int)ans;
}

int main()
{
    string s;
    cin >> s;
    cout << convert1(s) << endl;
}

CodePudding user response:

If you try printing s[s.length()] each time you call convert1, you'll see that it's printing 0. And then you're subtracting the value of '0' (48) from that.

Let's say we try to convert "12".

The length is not 1, so we call convert1 on "1".

That is of length 1, so we return 1.

So, if so is 1, and s[s.length()] is 0, then num is -48 and so * 10 num evaluates to 1 * 10 - 48 which is -38.

For a two digit number input, you will always see the first digit times 10, minus 48. For a three digit number, you'll see (the first digit * ten minus 48) times 10 minus 48. This pattern continues on. If the first digit is large enough, it times 10 minus 48 creates a positive number. If that's large enough, positive numbers continue to propagate through the recursion. If they ever get smaller than 48, then once the result is negative, it will just get larger as a negative number the more recursive calls are made.


As opposed to the way you have done things, you can employ an accumulator parameter in convert1.

int convert1(string s, int acc=0) {
    if (s.length() == 1) {
        return acc * 10   (s[0] - '0');
    }

    return convert1(s.substr(1, s.length() - 1), acc * 10   (s[0] - '0'));
}

Each time the function is recursively called, we update the accumulator by multiplying it by ten and adding the value of the first digit, and update the string by taking the "tail" of the string.

CodePudding user response:

The normal way

int main()
{
    string s;
    cin >> s;
    cout << strtol(s.c_str(), nullptr, 10) << endl;
}

Recursive for some reason

int convert_string(const char* string, int length){
   if (length == 0) {
      return 0;
   }

   int output = string[0] - '0';
   output *= pow(10, length - 1);
   output  = convert_string(&string[1], --length);
   return output;
}

int main()
{
    std::string s;
    std::cin >> s;
    std::cout << convert_string(s.c_str(), s.length()) << std::endl;
}
  • Related