CodingBat: Java. Recursion-1, Part II

countHi:

public int countHi(String str) {
	if (str.length() < 2) return 0;
	if (str.substring(0, 2).equals("hi"))
		return 1 + countHi(str.substring(2));
	return countHi(str.substring(1));
}

changeXY:

public String changeXY(String str) {
	if (str.length() == 0) return str;
	if (str.charAt(0) == 'x') return "y" + changeXY(str.substring(1));
	return str.charAt(0) + changeXY(str.substring(1));
}

changePi:

public String changePi(String str) {
	if (str.length() < 2) return str;
	if (str.substring(0, 2).equals("pi"))
		return "3.14" + changePi(str.substring(2));
	return str.charAt(0) + changePi(str.substring(1));
}

noX:

public String noX(String str) {
	if (str.length() == 0) return "";
	if (str.charAt(0) == 'x') return noX(str.substring(1));
	return str.charAt(0) + noX(str.substring(1));
}

array6:

public boolean array6(int[] nums, int index) {
	if (nums.length == 0) return false;
	if (index == nums.length - 1) return nums[index] == 6;
	if (nums[index] == 6) return true;
	return array6(nums, index + 1);
}

array11:

public int array11(int[] nums, int index) {
	if (index == nums.length) return 0;
	if (nums[index] == 11) return 1 + array11(nums, index + 1);
	return array11(nums, index + 1);
}

array220:

public boolean array220(int[] nums, int index) {
	if (nums.length < 2 || index == nums.length - 1) return false;
	if (nums[index + 1] == nums[index] * 10) return true;
	return array220(nums, index + 1);
}

allStar:

public String allStar(String str) {
	if (str.length() <= 1) return str;
	return str.charAt(0) + "*" + allStar(str.substring(1));
}

pairStar:

public String pairStar(String str) {
	if (str.length() < 2) return str;
	if (str.charAt(0) == str.charAt(1))
		return str.charAt(0) + "*" + pairStar(str.substring(1));
	return str.charAt(0) + pairStar(str.substring(1));
}

endX:

public String endX(String str) {
	if (str.length() == 0) return str;
	if (str.charAt(0) == 'x')
		return endX(str.substring(1)) + "x";
	return str.charAt(0) + endX(str.substring(1));
}

2 thoughts on “CodingBat: Java. Recursion-1, Part II

  1. WOJTEK

    A bit shorter

    public int countHi(String str) {
    if(str.length()==0) return 0;
    if(str.startsWith(“hi”))return 1+countHi(str.substring(1));
    return countHi(str.substring(1));
    }

    Reply
  2. WOJTEK

    A bit shorter

    public boolean array6(int[] nums, int index) {
    if(index==nums.length) return false;
    if(nums[index]==6) return true;
    return array6(nums, index+1);
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.