Java > AP-1 > copyEndy (CodingBat Solution)

Problem:

We'll say that a positive int n is "endy" if it is in the range 0..10 or 90..100 (inclusive). Given an array of positive ints, return a new array of length "count" containing the first endy numbers from the original array. Decompose out a separate isEndy(int n) method to test if a number is endy. The original array will contain at least "count" endy numbers.

copyEndy({9, 11, 90, 22, 6}, 2) → {9, 90}
copyEndy({9, 11, 90, 22, 6}, 3) → {9, 90, 6}
copyEndy({12, 1, 1, 13, 0, 20}, 2) → {1, 1}


Solution:

public int[] copyEndy(int[] nums, int count) {
  int ctr = 0;
  int[] array = new int[count];
  for (int i = 0; i < nums.length; i++) {
    if (isEndy(nums[i])) {
      array[ctr] = nums[i];
      ctr++;      
    }
    if (ctr == count)
      return array;
  }
  return array;
}

private boolean isEndy(int n) {
  return (n >= 0 && n <= 10) || (n <= 100 && n >= 90);
}


No comments :

Post a Comment

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