0

Possible Duplicate:
Write a recursive function that reverses the input

Recently, I've been reading the book C++ For Everyone and I've been having trouble putting together a recursive function (Confusing to think about...)

The question was: Write a recursive function string reverse(string str) that returns the reverse of str

This is what I have so far:

string reverse(string str)
{
    string word = "";

    if (str.length() <= 1)
    {
        return str;
    }
    else
    {
        string str_copy = str;
        int n = str_copy.length() - 1;
        string last_letter = str_copy.substr(n, 1);

        str_copy = str_copy.substr(0, n);
        word += reverse(str_copy);
        return last_letter;
    }
    return word;
}

My problems now is:

If I enter wolf, it returns f

If I change return last_letter to return word, I get w

If I change to return str_copy, I get wol

Community
  • 1
  • 1
Alex
  • 3,111
  • 6
  • 27
  • 43

2 Answers2

3

You need to return the combination of the the last character (last_letter) and the reversal of the rest of the string, but you don't do that in any of your attempts. You only ever return one part or the other.

string reverse(string str)
{
    int len = str.length();
    if (len <= 1)
    {
        return str;
    }
    else
    {
        return str.substr(len-1, 1) + reverse( str.substr(0, len-1) );
    }
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Off by one error -- should be `reverse( str.substr(0, len-1) );` otherwise the inner `reverse` has the same `str` as the outer `reverse`. – user470379 Apr 23 '11 at 00:40
1

This would do the work:

Delete return last_letter;

Change `

word += reverse(str_copy);

to

word = last_letter+reverse(str_copy);

I'll leave the thinking to you!

Best.

zw324
  • 26,764
  • 16
  • 85
  • 118