Java > Array-1 > midThree (CodingBat Solution)

Problem:

Given an array of ints of odd length, return a new array length 3 containing the elements from the middle of the array. The array length will be at least 3.

midThree({1, 2, 3, 4, 5}) → {2, 3, 4}
midThree({8, 6, 7, 5, 3, 0, 9}) → {7, 5, 3}
midThree({1, 2, 3}) → {1, 2, 3}


Solution:

public int[] midThree(int[] nums) {
  return new int[] {
  nums[(nums.length+1)/2 -2],
  nums[(nums.length+1)/2 -1],
     nums[(nums.length+1)/2]};
}


2 comments :

  1. public int[] midThree(int[] nums) {

    int nn[] = {nums[nums.length/2-1], nums[nums.length/2], nums[nums.length/2+1 ]};


    return nn;

    ReplyDelete
  2. public int[] midThree(int[] nums) {
    int[] newArr = new int[3];
    if(nums.length==3)
    return nums;
    else

    newArr[0]=nums[nums.length/2-1];
    newArr[1]=nums[nums.length/2];
    newArr[2]=nums[nums.length/2+1];
    return newArr;
    }

    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