Java > Array-1 > makeEnds (CodingBat Solution)

Problem:

Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more.

makeEnds({1, 2, 3}) → {1, 3}
makeEnds({1, 2, 3, 4}) → {1, 4}
makeEnds({7, 4, 6, 2}) → {7, 2}


Solution:

public int[] makeEnds(int[] nums) {
  int[] myArray = new int[2];
  if (nums.length == 1) {
    myArray[0] = nums[0];
    myArray[1] = nums[0];
  } else {
    myArray[0] = nums[0];
    myArray[1] = nums[nums.length-1];
  }
  
  return myArray;
}


11 comments :

  1. it also can be done as:-

    public int[] makeEnds(int[] nums)
    {
    int arr[] = new int[2];
    arr[0] = nums[0];
    arr[1] = nums[nums.length-1];
    return arr;
    }

    ReplyDelete
  2. simplest form:


    public int[] makeEnds(int[] nums) {
    return new int[] {nums[0], nums[nums.length-1]};
    }

    ReplyDelete
  3. public int[] makeEnds(int[] nums) {
    int [] first = new int[] {nums[0]};
    if (nums.length == 2)
    return nums;
    int[] firstLast = new int[] {nums[0], nums[nums.length -1]};
    return firstLast;
    }

    ReplyDelete
  4. almost same as above:
    public int[] makeEnds(int[] nums) {
    int[] rtn = {nums[0], nums[nums.length-1]};
    return rtn;
    }

    ReplyDelete
  5. public int[] makeLast(int[] nums) {
    int [] arr = new int[nums.length * 2];

    arr[arr.length-1] = nums[nums.length-1];

    return arr;

    }

    ReplyDelete
  6. public int[] makeEnds(int[] nums) {

    int [] arr = new int [] {nums[0], nums[nums.length-1]};
    return arr;

    ReplyDelete
  7. public int[] makeEnds(int[] nums) {

    if (nums.length==1) return new int [] {nums[0],nums[0]};
    else return new int [] {nums[0],nums[nums.length-1]};
    }

    ReplyDelete
  8. public int[] makeEnds(int[] nums) {
    int a[]={(nums[0]),(nums[nums.length-1])};
    return a;
    }

    ReplyDelete
  9. i from uzbekistan

    public int[] makeEnds(int[] nums) {

    return new int[] {nums[0],nums[nums.length -1]};
    }

    perfect one return

    ReplyDelete
  10. public int[] makeEnds(int[] nums) {
    if(nums.length>1){
    int[] arr=new int[]{nums[0],nums[(nums.length)-1]};
    return arr;
    }
    else{
    int[] a=new int[]{nums[0],nums[0]};
    return a;
    }
    }

    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