Sunday, April 17, 2016

[Java][Answer] Array-1 > makeLast()

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]

Answer 1

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

Answer 2

public int[] makeLast(int[] nums) {
  int[] tempArr = new int[nums.length*2];
  for(int i=0; i<tempArr.length; i++){
    tempArr[i] = 0;
  }
  tempArr[tempArr.length-1] = nums[nums.length-1];
  return tempArr;
}

To use answer 1, firstly you need to know by default int array element default element is 0.

Reference
http://www.javaproblems.com/2012/12/coding-bat-java-array-1-makelast.html

No comments :

Post a Comment