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; }
it also can be done as:-
ReplyDeletepublic int[] makeEnds(int[] nums)
{
int arr[] = new int[2];
arr[0] = nums[0];
arr[1] = nums[nums.length-1];
return arr;
}
simplest form:
ReplyDeletepublic int[] makeEnds(int[] nums) {
return new int[] {nums[0], nums[nums.length-1]};
}
public int[] makeEnds(int[] nums) {
ReplyDeleteint [] first = new int[] {nums[0]};
if (nums.length == 2)
return nums;
int[] firstLast = new int[] {nums[0], nums[nums.length -1]};
return firstLast;
}
almost same as above:
ReplyDeletepublic int[] makeEnds(int[] nums) {
int[] rtn = {nums[0], nums[nums.length-1]};
return rtn;
}
public int[] makeLast(int[] nums) {
ReplyDeleteint [] arr = new int[nums.length * 2];
arr[arr.length-1] = nums[nums.length-1];
return arr;
}
public int[] makeEnds(int[] nums) {
ReplyDeleteint [] arr = new int [] {nums[0], nums[nums.length-1]};
return arr;
forgot the last bracket on bottom of code
Delete"}"
public int[] makeEnds(int[] nums) {
ReplyDeleteif (nums.length==1) return new int [] {nums[0],nums[0]};
else return new int [] {nums[0],nums[nums.length-1]};
}
public int[] makeEnds(int[] nums) {
ReplyDeleteint a[]={(nums[0]),(nums[nums.length-1])};
return a;
}
i from uzbekistan
ReplyDeletepublic int[] makeEnds(int[] nums) {
return new int[] {nums[0],nums[nums.length -1]};
}
perfect one return
public int[] makeEnds(int[] nums) {
ReplyDeleteif(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;
}
}