Reverse a String using Recursion
Reverse a string using recursion instead of a loop.
Sample input
hello
Sample output
olleh
Solution
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
print(reverse("hello"))
function reverse(s) {
if (s.length <= 1) return s;
return reverse(s.slice(1)) + s[0];
}
console.log(reverse("hello"));
public class Main {
static String reverse(String s) {
if (s.length() <= 1) return s;
return reverse(s.substring(1)) + s.charAt(0);
}
public static void main(String[] args) {
System.out.println(reverse("hello"));
}
}
fun reverse(s: String): String {
if (s.length <= 1) return s
return reverse(s.substring(1)) + s[0]
}
fun main() {
println(reverse("hello"))
}
func reverse(_ s: String) -> String {
if s.count <= 1 { return s }
return reverse(String(s.dropFirst())) + String(s.first!)
}
print(reverse("hello"))
String reverse(String s) {
if (s.length <= 1) return s;
return reverse(s.substring(1)) + s[0];
}
void main() {
print(reverse("hello"));
}
#include <iostream>
#include <string>
using namespace std;
string reverseStr(const string& s) {
if (s.size() <= 1) return s;
return reverseStr(s.substr(1)) + s[0];
}
int main() {
cout << reverseStr("hello") << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
void reverse(const char *s, int index, int len) {
if (index == len) return;
reverse(s, index + 1, len);
putchar(s[index]);
}
int main() {
char s[] = "hello";
reverse(s, 0, strlen(s));
putchar('\n');
return 0;
}