All puzzles
Per page
Z
Recursion ยท String

Count the x's

Return how many times "x" appears in the String s. Do not use a loop. Count the x's in the rest of the String, then add 1 if the first letter is "x".

countX("xaxbx") returns 3.

11 strips: Z1 to Z11

}
Z1
return 0;
Z2
int rest = countX(s);
Z3
int rest = countX(s.substring(1));
Z4
return rest + 1;
Z5
}
Z6
if (s.length() == 0) {
Z7
return rest;
Z8
public static int countX(String s) {
Z9
}
Z10
if (s.substring(0, 1).equals("x")) {
Z11

Answer key: Z. Count the x's

Order: Z9, Z7, Z2, Z1, Z4, Z11, Z5, Z10, Z8, Z6. Extra: Z3

public static int countX(String s) {
	if (s.length() == 0) {
		return 0;
	}
	int rest = countX(s.substring(1));
	if (s.substring(0, 1).equals("x")) {
		return rest + 1;
	}
	return rest;
}

Extra strip: int rest = countX(s);. countX(s) calls the method on the same String, so it never gets shorter. The calls never stop, and Java throws a StackOverflowError.