Java > Array-1 > start1 (CodingBat Solution)

Problem:

Start with 2 int arrays, a and b, of any length. Return how many of the arrays have 1 as their first element.

start1({1, 2, 3}, {1, 3}) → 2
start1({7, 2, 3}, {1}) → 1
start1({1, 2}, {}) → 1


Solution:

public int start1(int[] a, int[] b) {
  int count = 0; 
  if (a.length > 0 && a[0] == 1)
    count++;
  if (b.length > 0 && b[0] ==1)
    count++;
  return count;
 
}


3 comments :


  1. public int start1(int[] a, int[] b) {

    int count = 0;

    if (a.length > 0 && a[0] == 1)

    count++;

    if (b.length > 0 && b[0] ==1)

    count++;

    return count;



    }

    ReplyDelete
  2. Wow... I implemented the wrong algorithm but still worked, just less efficient. I thought I needed to count the number of occurrences of the int 1 in both arrays, so I got this:

    public int start1(int[] a, int[] b) {

    int count = 0;
    int len = Math.max(a.length, b.length);

    for(int i = 0; i < len; ++i) {
    if(i < b.length && b[i] == 1)
    count += 1;
    if(i < a.length && a[i] == 1)
    count += 1;
    }

    return count;
    }

    ReplyDelete
  3. public int start1(int[] a, int[] b) {

    int n=0;
    if(a.length>=1 && a[0]==1)
    n++;
    if(b.length>=1 && b[0]==1)
    n++;

    return n;

    }

    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