Java > Array-1 > makeLast (CodingBat Solution)

Problem:

Given an int array, return a new array with double the length where its last element is the same as the original array, and all the other elements are 0. The original array will be length 1 or more. Note: by default, a new int array contains all 0's.

makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}


Solution:

public int[] makeLast(int[] nums) {
  int len = nums.length;
  int[] myArray = new int[2*len];
  myArray[myArray.length-1] = nums[len-1];
  return myArray;
}

3 comments:

  1. public int[] makeLast(int[] nums) {
    int len = nums.length;
    int[] bs = new int[2*len];
    bs[bs.length-1] = nums[len-1];
    return bs;
    }

    ReplyDelete
  2. private final int[] makeLast(int[] nums) {
    final int[] intArray = new int[nums.length * 2];
    intArray[intArray.length - 1] = nums[nums.length - 1];
    return intArray;
    }

    ReplyDelete
  3. public int[] makeLast(int[] nums) {
    int[]a=new int[2*nums.length];
    a[a.length-1]=nums[nums.length-1];
    return a;
    }

    ReplyDelete