Problem:
Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string.
countX("xxhixx") → 4
countX("xhixhix") → 3
countX("hi") → 0
Solution:
public int countX(String str) { if (str.equals("")) return 0; if (str.charAt(0) == 'x') return 1 + countX(str.substring(1)); else return countX(str.substring(1)); }
public int countX(String str) {
ReplyDeleteint i = str.indexOf("x");
if (i != -1) {
return 1 + countX(str.substring(i + 1));
}
else
return 0;
}
public int countX(String str) {
ReplyDeleteint counter=0;
if(counter==str.length()){
return 0;
}
if(str.charAt(counter)=='x')
{
counter=counter+1;
}
return counter+countX(str.substring(1));
}
public int countX(String str) {
ReplyDeleteif (str.isEmpty())
return 0;
int x = str.charAt(0)=='x' ? 1 : 0;
return x + countX(str.substring(1));
}
int count=0;
ReplyDeletefor (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='x')
count++;
}
return count;