Created
June 3, 2020 08:59
-
-
Save bhaveshmunot1/0eceb036969dcd51980ad072b67cc00c to your computer and use it in GitHub Desktop.
Reverse a string using recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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