CodingBat: Java. Warmup-1, Part III


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


Here are the final ten exercises from the Warmup-1 section of CodingBat.

mixStart:

	public boolean mixStart(String str) {
		return str.length() >= 3 && str.substring(1, 3).equals("ix");
	}

startOz:

	public String startOz(String str) {
		String result = "";
		if (str.length() > 0 && str.charAt(0) == 'o') result += 'o';
		if (str.length() > 1 && str.charAt(1) == 'z') result += 'z';
		return result;
	}

intMax:

	public int intMax(int a, int b, int c) {
		int max = a;
		if (b > max) max = b;
		if (c > max) max = c;		
		return max;
	}

The solution on the website first compares a and b and assigns the greater value to the variable max. This step can be condensed to assigning a to max right away and then check whether b is greater than max.

close10:

	public int close10(int a, int b) {
		if (Math.abs(10 - a) == Math.abs(10 - b)) return 0;
		if (Math.abs(10 - a) < Math.abs(10 - b)) return a;
		return b;
	}

in3050:

	public boolean in3050(int a, int b) {
		boolean condition1 = a >= 30 && a <= 40 && b >= 30 && b <= 40;
		boolean condition2 = a >= 40 && a <= 50 && b >= 40 && b <= 50;
		return condition1 || condition2;
	}

max1020:

	public int max1020(int a, int b) {
		if (b < a) {
			int temp = a;
			a = b;
			b = temp;
		}
		boolean aInRange = a >= 10 && a <= 20;
		boolean bInRange = b >= 10 && b <= 20;
		if (aInRange && bInRange || !aInRange && bInRange)
			return b;
		if (aInRange && !bInRange)
			return a;
		return 0;
	}

stringE:

	public boolean stringE(String str) {
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == 'e') count++;
		}
		return (count >= 1 && count <= 3);
	}

lastDigit:

	public boolean lastDigit(int a, int b) {
		return (Math.abs(a - b) % 2 == 0);
	}

endUp:

	public String endUp(String str) {
		if (str.length() <= 3) return str.toUpperCase();
		return str.substring(0, str.length() - 3)
				+ str.substring(str.length() - 3).toUpperCase();
	}

everyNth:

	public String everyNth(String str, int n) {
		String result = "";
		for (int i = 0; i < str.length(); i++) {
			if (i % n == 0) result += str.charAt(i);
		}
		return result;
	}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.