Java > Array-1 > makeMiddle (CodingBat Solution)

Problem:

Given an array of ints of even length, return a new array length 2 containing the middle two elements from the original array. The original array will be length 2 or more.

makeMiddle({1, 2, 3, 4}) → {2, 3}
makeMiddle({7, 1, 2, 3, 4, 9}) → {2, 3}
makeMiddle({1, 2}) → {1, 2}

Solution:

public int[] makeMiddle(int[] nums) {
int[] myArray = new int[2];
int middle = nums.length / 2;

myArray[0] = nums[middle - 1];
myArray[1] = nums[middle];

return myArray;
}


1 comment :

  1. public int[] makeMiddle(int[] nums) {
    int sum=((nums.length/2));
    int diff=((nums.length/2)-1);
    int[] arr=new int[]{nums[diff], nums[sum]};
    return arr;
    }

    ReplyDelete

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