0

I have this recursion here, when I input "ello", the output returns "ello". I thought it would return "ellllloo". Am I not following the recursion right? It's keep calling FN(str.substring(1));

            return str.substring(0, 1) + FN(str.substring(1));
4
  • 5
    Pencil and a paper for the rescue. Commented May 5, 2015 at 11:16
  • Side note: you can use 'isEmpty()' instead of querying the length and comparing to 0. And you might want to rework your question until it becomes clear what exactly your recursion should yield as output. Right now, the only thing that can be said is: your recursion is based on letters being a or h; and both letters do not show up in your input. So you always take the "then" path of the second if. What is the surprise there? Commented May 5, 2015 at 11:16
  • return str.substring(0, 1) + FN(str.substring(1)). yes, so with this "ello", it returns "el"+FN("llo"), and so on, that wouldn't output "ello", but I'm getting "ello" in the output Commented May 5, 2015 at 11:25
  • ahh i thought the end index is inclusive Commented May 5, 2015 at 11:27

3 Answers 3

4

There is no 'a' or 'h' in the input, so it will always call return str.substring(0, 1) + FN(str.substring(1)); until the length is 0 :

FN("ello") = 
   "e" + FN("llo") = 
   "e" + "l" + FN("lo") = .... = "ello"
Sign up to request clarification or add additional context in comments.

Comments

1

Use

str.substring(0, 2)// instead of str.substring(0, 1)

Comments

1

Your recursion each time takes the first letter of the remaining string:

  "e" + FN("llo")
= "e" +    "l"   + FN("lo") 
= "e" +    "l"   + "l"     + FN("o") = "ello"

Comments

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.