Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Reverse a string using recursion.
string reverse(string s) {
int length = s.size();
if (length <= 1) {
return s;
string middle_part = string(s.begin()+1, s.end()-1);
string reversed_middle_part = reverse(middle_part);
string first_char = string(s.begin(), s.begin()+1);
string last_char = string(s.end()-1, s.end());
string reversed = last_char + reversed_middle_part + first_char;
return reversed;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.