Java > Array-1 > biggerTwo (CodingBat Solution)

Problem:

Start with 2 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.

biggerTwo({1, 2}, {3, 4}) → {3, 4}
biggerTwo({3, 4}, {1, 2}) → {3, 4}
biggerTwo({1, 1}, {1, 2}) → {1, 2}


Solution:

public int[] biggerTwo(int[] a, int[] b) {
  int aTotal = a[0] + a[1];
  int bTotal = b[0] + b[1];
  
  if (aTotal == bTotal)
    return a;
  else if (aTotal > bTotal)
    return a;
  else
    return b;
  
  
}


2 comments :

  1. public int[] biggerTwo(int[] a, int[] b) {
    if (a[0]+a[1]>=b[0]+b[1]) return a;
    else return b;
    }

    ReplyDelete
  2. public int[] biggerTwo(int[] a, int[] b) {

    if (b[0] + b[1] > a[0] + a[1]) return b;
    else return a;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact