0

Why this return the string reversed, and why this is a recursion function?

public static String Reverse(String a){                                 
        String result = "";
        if(a.length()>0){
            result = Reverse(a.substring(1))+a.charAt(0);
        }
        return result;
    }
12
  • Is it a reverse function? Have you tested it? Commented Apr 4, 2020 at 20:17
  • 1
    I don't think the function is recursive either. Commented Apr 4, 2020 at 20:19
  • 4
    @markspace - Yes, this is a recursive function that reverses a String. I'm not sure of the reason behind your comments. Commented Apr 4, 2020 at 20:20
  • 2
    @Hana I would recommend you step through this with your debugger, to find out how it does what it does. That would be worth 1000 words of explanation. Commented Apr 4, 2020 at 20:21
  • 1
    @markspace have you tried it? Because from here it looks correct and recursive. Commented Apr 4, 2020 at 20:21

1 Answer 1

3

It can be defined in steps:

  1. Split any string into first character and the 'rest'.
  2. If the 'rest' length is greater than 0, then repeat step 1 for input 'rest'

  3. When the recursion will get to the last character, it will start to print the characters in reverse.

The last recursive execution will return a empty string. To this empty statement it will add character from the previous call (n-1 character), then to this it will add character from position (n-2), and so on. This way we will get a recursive function:

  public static String reverse(String a){   
    if(a.length()>0){
        return reverse(a.substring(1))+a.charAt(0);
    }
    return ""; // last statement
 }

Example:

 'cat' -> reverse('at') + 'c'
          (reverse('t') + 'a') + 'c'
          ((reverse('') + 't') + 'a' + 'c')
          => 'tac'
Sign up to request clarification or add additional context in comments.

1 Comment

When a.length<1, then it can only be an empty string. So no difference there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.