I recently got asked this during an interview. As a recent graduate, and only been programming about 2 years (all school work), I was at a loss. I had a vague idea, but I’m sure I failed it. This is what I’d written:
string Reverse(string word, string reversed)
{
if(word.length() == 0)
{
return reversed;
}
else
{
string temp;
reversed = word.substr(0,1) + reversed;
temp = word.substr(1);
Reverse(temp, reversed);
}
return reversed;
}
Now that I’m home, I’m testing it, and the return is only the first letter in the input. I’m vaguely familiar with the concept of recursion, but I’m obviously failing at this. Any help/pointers/suggestions are very much appreciated. Thank you.
EDIT:
Following Dennis Meng’s post, I’ve made the following change:
string Reverse(string word, string reversed)
{
if(word.length() == 0)
{
return reversed;
}
else
{
string temp;
reversed = word.substr(0,1) + reversed;
temp = word.substr(1);
return Reverse(temp, reversed);
}
}
Now, I get the proper return value. Thank you so very much.
What’s going wrong is in here:
You know that the call should return the correct answer, so why not just return that? In other words, what if you did
instead? The specifics of why your code was only returning the first letter involves pass-by-reference/pass-by-value; because of the pass-by-value stuff, you never actually used what was done in the recursive calls. (You just made the call and threw away what it returned.)