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) {
  if (nums.length == 1)
  return new int[] {nums[0]};
  else if (nums.length == 0)
  return new int[] {};
  else 
  return new int[] {nums[0],nums[1]};
}


10 comments :

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

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

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

    ReplyDelete
  4. int [] dizi=new int[2];
    if(nums.length>=2)
    {dizi[0]=nums[0];
    dizi[1]=nums[1];
    return dizi;
    }
    else
    return nums;

    ReplyDelete
  5. public int[] frontPiece(int[] nums)
    {
    if (nums.length <= 2)
    {
    int[] len = nums;
    return len;
    }
    else
    {
    int[] leng = {nums[0],nums[1]};
    return leng;
    }
    }

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

    for(int i=0;i<2;i++){
    if(nums.length>1){
    return new int[]{nums[0],nums[1]};
    }
    }
    return nums;
    }

    ReplyDelete
  7. public int[] frontPiece(int[] nums) {
    return nums.length>1? new int[]{nums[0], nums[1]} : nums;
    }

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

    ReplyDelete
  9. public int[] frontPiece(int[] nums) {
    if(nums.length>1){
    int firstTwo[] = {nums[0],nums[1]};
    return firstTwo;
    }else
    return nums;
    }

    ReplyDelete
  10. if(nums.length>2){
    return new int [] {nums[0], nums[1]};
    }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