While practicing Java problems on coding bat I came across this problem. Though I have solved this problem, I was wondering if I could get a solution with a fewer if-else statement. Can you help me with this?
Question:
Start with two int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.
Example:-
biggerTwo([1, 2], [3, 4]) → [3, 4]
biggerTwo([3, 4], [1, 2]) → [3, 4]
biggerTwo([1, 1], [1, 2]) → [1, 2]
My Solution:-
public int[] biggerTwo(int[] a, int[] b) {
if(a[0]+a[1]==b[0]+b[1]){
return a;
}
else if(a[0]+a[1]>b[0]+b[1]){
return a;
}else{
return b;
}
}
Aucun commentaire:
Enregistrer un commentaire