Skip to content

Instantly share code, notes, and snippets.

@asa55
Created April 3, 2020 22:35
Show Gist options
  • Save asa55/e4db28286f6f714c86fe8545f6f0bd5b to your computer and use it in GitHub Desktop.
Save asa55/e4db28286f6f714c86fe8545f6f0bd5b to your computer and use it in GitHub Desktop.
// How can a given string be reversed using recursion?
#include <iostream>
#include <string>
std::string reverse( const std::string& str )
{
std::string _str = str;
if ( _str.size() > 1 )
return reverse( _str.substr( 1, _str.size() - 1 ) ).append( _str.substr( 0, 1 ) );
else return _str;
}
int main ()
{
std::string my_str = "abcd";
my_str = reverse( my_str );
std::cout << my_str << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment