Problem:
Given 2 int arrays, each length 2, return a new array length 4 containing all their elements.
plusTwo({1, 2}, {3, 4}) → {1, 2, 3, 4}
plusTwo({4, 4}, {2, 2}) → {4, 4, 2, 2}
plusTwo({9, 2}, {3, 4}) → {9, 2, 3, 4}
Solution:
public int[] plusTwo(int[] a, int[] b) { int[] myArray = new int[4]; myArray[0] = a[0]; myArray[1] = a[1]; myArray[2] = b[0]; myArray[3] = b[1]; return myArray; }
public int[] plusTwo(int[] a, int[] b) {
ReplyDeleteint[] s = {a[0],a[1],b[0],b[1]};
return s;
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeletereturn new int[] {a[0], a[1], b[0], b[1]};
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeleteint[] c = new int[4];
c[0]=a[0];
c[1]=a[1];
c[2]=b[0];
c[3]=b[1];
return c;
}
This will work for arrays of any length.
ReplyDeletepublic int[] plusTwo(int[] a, int[] b) {
int[] sum = new int[a.length + b.length];
int i = 0;
for(; i < a.length; i++) {
sum[i] = a[i];
}
for(; i < b.length + a.length; i++) {
sum[i] = b[i - a.length];
}
return sum;
}
the shortest way
ReplyDeletepublic int[] plusTwo(int[] a, int[] b) {
return new int[] {a[0],a[1],b[0],b[1]};
}
public int[] plusTwo(int[] a, int[] b)
ReplyDelete{
return new int[] {a[0], a[1],b[0], b[1]};
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeleteint[] connect = { a[0], a[1], b[0], b[1] };
return connect;
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeleteint[] newArr = {a[0],a[1],b[0],b[1]};
return newArr;
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeletereturn new int[] {a[0],a[1],b[0],b[1]};
}
public int[] plusTwo(int[] a, int[] b) {
ReplyDeleteint[] arr=new int[]{a[0],a[1],b[0],b[1]};
return arr;
}