I am trying the coding bat problem repeatFront:
Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n = 0 and n <= str.length()).
repeatFront("Chocolate", 4) → "ChocChoChC" repeatFront("Chocolate", 3) → "ChoChC" repeatFront("Ice Cream", 2) → "IcI"
Here is the code I am trying:
public String repeatFront(String str, int n) {
if(n==0) {
return str;
}
sub = str.substring(0,n);
sub = sub+repeatFront(sub,n-1);
return sub;
}
The error I get is that there is an extra character at the end of my string. The first example would give "ChocChoChCC" and the second "ChoChCC" and so on. I just want to know, conceptually, what I am doing wrong and how to fix it.
Ah I found your problem.
You must only return the empty string if
n == 0
.Returning
str
will return that extra last letter a second time as the callrepeatFront(Ch, 1)
andrepeatFront(C, 0)
both returnC
.Fix by changing the return on
n==0
toreturn "";
: