Sunday, April 19, 2015

[Java][Answer] CodingBat Array-1 > swapEnds()

Given an array of ints, swap the first and last elements in the array. Return the modified array. The array length will be at least 1.

swapEnds([1, 2, 3, 4]) → [4, 2, 3, 1]
swapEnds([1, 2, 3]) → [3, 2, 1]
swapEnds([8, 6, 7, 9, 5]) → [5, 6, 7, 9, 8]

Answer 1:
public int[] swapEnds(int[] nums) {
  int tempInt = nums[0];
  nums[0] = nums[nums.length-1];
  nums[nums.length-1] = tempInt;
  return nums;
}
Answer 2:
public int[] swapEnds(int[] nums) {
int a = nums[0];
int b = nums[nums.length - 1];
nums[0] = b;
nums[nums.length - 1] =a;
  return nums;
}

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

No comments :

Post a Comment