CodingBat: Java. AP-1, Part II

hasOne:

public boolean hasOne(int n) {
	while (n > 0) {
		if (n % 10 == 1) return true;
		n = n / 10;
	}
	return false;
}

dividesSelf:

public boolean dividesSelf(int n) {
	int copyN = n;
	while (n > 0)
		if (n % 10 == 0) return false;
		else
			if (copyN % (n % 10) == 0) n /= 10;
			else return false;
	return true;
}

copyEvens:

public int[] copyEvens(int[] nums, int count) {
	int[] result = new int[count];
	int position = 0;

	for (int i = 0; i < nums.length; i++) {
		if (nums[i] % 2 == 0) {
			result[position] = nums[i];
			position++;
		}
		if (position == count) break;
	}
	return result;
}

copyEndy:

public int[] copyEndy(int[] nums, int count) {
	int[] result = new int[count];
	for (int i = 0, pos = 0; i < nums.length; i++) {
		if (nums[i] >= 0 && nums[i] <= 10 || nums[i] >= 90
				&& nums[i] <= 100) {
			result[pos] = nums[i];
			pos++;
		}
		if (pos == count) break;
	}
	return result;
}

matchUp:

public int matchUp(String[] a, String[] b) {
	int count = 0;
	for (int i = 0; i < a.length; i++)
		if (!a[i].equals("") && !b[i].equals("")
				&& a[i].charAt(0) == b[i].charAt(0))
			count++;
	return count;
}

scoreUp:

public int scoreUp(String[] key, String[] answers) {
	int sum = 0;
	for (int i = 0; i < answers.length; i++)
		if (answers[i] == key[i]) sum += 4;
		else if (!answers[i].equals("?")) sum -= 1;
	return sum;
}

wordsWithout:

public String[] wordsWithout(String[] words, String target) {
	int count = 0;
	for (int i = 0; i < words.length; i++)
		if (!words[i].equals(target)) count++;

	String[] result = new String[count];
	for (int i = 0, pos = 0; i < words.length; i++)
		if (!words[i].equals(target)) {
			result[pos] = words[i];
			pos++;
		}
	return result;
}

7 thoughts on “CodingBat: Java. AP-1, Part II

    1. Gregor Ulm Post author

      Denis, both expressions are equivalent. If this isn’t clear to you, then maybe draw a number line and mark the segments for x >= 1 and x > 0.

      Reply
    1. Raymond

      Its not really an issue, you can just take the if condition and put it in the other method…

      public int[] copyEndy(int[] nums, int count) {
      int[] result = new int[count];
      for (int i = 0, pos = 0; i = 0 && n = 90 && n <= 100)
      return true;

      return false;
      }

      Reply
      1. Raymond

        not sure why the coding didn’t copy or if the comment is not showing properly…

        public boolean isEndy(int n) {
        if (n >= 0 && n = 90 && n <= 100)
        return true;

        return false;
        }

        Reply
  1. Maxim

    @scoreUp

    You are comparing two strings with the == sign instead of .equals(). Your solution happens to give correct answers but I don’t think it’s correct practice to compare strings with the == sign.

    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.