Thursday, March 19, 2015

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

Given 2 int arrays, a and b, of any length, return a new array with the first element of each array. If either array is length 0, ignore that array.

front11([1, 2, 3], [7, 9, 8]) → [1, 7]
front11([1], [2]) → [1, 2]
front11([1, 7], []) → [1]

Answer 1:
public int[] front11(int[] a, int[] b) {
  if(a.length==0 && b.length==0 ) return new int[0];
  else if(a.length==0 || b.length==0 ){
    if(a.length == 0) return new int[]{b[0]};
    if(b.length == 0) return new int[]{a[0]};
  }
  return new int[]{a[0],b[0]};
}
Answer 2:
public int[] front11(int[] a, int[] b) {
  if (a.length == 0 && b.length == 0)
  return new int[] {};
 
  else if (a.length !=0 && b.length == 0)
  return new int[]{a[0]};
 
  else if (a.length == 0 && b.length != 0)
  return new int[]{b[0]};
  else
  return new int[] {a[0],b[0]};
}
Reference
http://www.javaproblems.com/2012/12/coding-bat-java-array-1-front11.html

No comments :

Post a Comment