Recursion

AP Computer Science A· difficulty 3/5

public static String rev(String s) {
    if (s.length() <= 1) return s;
    return rev(s.substring(1)) + s.charAt(0);
}
System.out.println(rev("abcd"));

What is printed?

  • A

    dcba

    check_circle
  • B

    abc

  • C

    abcd

  • D

    dabc

Explanation

Each call moves the first character to the end of the recursively reversed remainder.

Want 10 more like this — adaptive to your weak spots?

Related questions