Java > Array-1 > frontPiece (CodingBat Solution)

Problem:

Given an int array of any length, return a new array of its first 2 elements. If the array is smaller than length 2, use whatever elements are present.

frontPiece({1, 2, 3}) → {1, 2}
frontPiece({1, 2}) → {1, 2}
frontPiece({1}) → {1}


Solution:

public int[] frontPiece(int[] nums) {
  int[] myArray = new int[2];

  if (nums.length < 2)
    return nums;
  else {
    myArray[0] = nums[0];
    myArray[1] = nums[1];
    return myArray;
  }
}


5 comments :

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

    return (nums.length <= 1)? nums : new int[]{nums[0], nums[1]};
    }

    ReplyDelete
  2. public int[] frontPiece(int[] nums) {

    return (nums.length <= 1)? nums : new int[]{nums[0], nums[1]};
    }

    ReplyDelete
  3. public int[] frontPiece(int[] nums) {
    if(nums.length>=2)
    return new int[]{nums[0],nums[1]};
    return nums;
    }

    ReplyDelete
  4. public int[] frontPiece(int[] nums) {
    return nums.length>1?Arrays.copyOfRange(nums,0,2):nums;
    }

    ReplyDelete
  5. public int[] frontPiece(int[] nums) {
    if(nums.length>=2){
    int[] arr = new int[]{ nums[0] ,nums[1]};
    return arr;
    }
    else {
    return nums;
    }
    }

    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