Java > AP-1 > copyEvens (CodingBat Solution)

Problem:

Given an array of positive ints, return a new array of length "count" containing the first even numbers from the original array. The original array will contain at least "count" even numbers.

copyEvens({3, 2, 4, 5, 8}, 2) → {2, 4}
copyEvens({3, 2, 4, 5, 8}, 3) → {2, 4, 8}
copyEvens({6, 1, 2, 4, 5, 8}, 3) → {6, 2, 4}


Solution:

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


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