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 |
Hisoka's Jutsu :
1 2 3 4 5 | public int countX(String str) { if (str.length() == 0) return 0; if(str.charAt(str.length()-1) == 'x') return 1+countX(str.substring(0, str.length()-1)); return countX(str.substring(0, str.length()-1)); } |
Output :
Ooowh... btw... if we want to write countX in C#, it will gonna be like this :
1 2 3 4 5 6 7 | public static int countX(String str) { //stop condition if (str.Length == 0) return 0; if (str[(str.Length - 1)] == 'x') return 1 + countX(str.Substring(0, str.Length - 1)); return countX(str.Substring(0, str.Length - 1)); } |
No comments:
Post a Comment