Java > Recursion-1 > countX (CodingBat Solution)

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));
}


4 comments :

  1. public int countX(String str) {
    int i = str.indexOf("x");
    if (i != -1) {
    return 1 + countX(str.substring(i + 1));
    }
    else
    return 0;
    }

    ReplyDelete
  2. public int countX(String str) {
    int counter=0;
    if(counter==str.length()){
    return 0;
    }

    if(str.charAt(counter)=='x')
    {
    counter=counter+1;

    }
    return counter+countX(str.substring(1));
    }

    ReplyDelete
  3. public int countX(String str) {
    if (str.isEmpty())
    return 0;

    int x = str.charAt(0)=='x' ? 1 : 0;

    return x + countX(str.substring(1));
    }

    ReplyDelete
  4. int count=0;
    for (int i = 0; i < str.length(); i++) {
    if(str.charAt(i)=='x')
    count++;
    }
    return count;

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact