Java > Warmup-2 > arrayFront9 (CodingBat Solution)

Problem:

Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.

arrayFront9({1, 2, 9, 3, 4}) → true
arrayFront9({1, 2, 3, 4, 9}) → false
arrayFront9({1, 2, 3, 4, 5}) → false


Solution:

public boolean arrayFront9(int[] nums) {
  int len = nums.length;
  
  if (len <= 4){
    for (int i = 0; i < len; i++){
      if (nums[i] == 9)
        return true;
      else;
    }
  } else {
      for (int j = 0; j < 4; j++) {
        if (nums[j] == 9)
          return true;
        else;
      }
    }
    
  return false;
}


2 comments :

  1. int count = 0;
    for (int i : nums) { count++;
    if ( i== 9) { return true;}
    if (count==4) break;
    }
    return false;

    ReplyDelete
    Replies
    1. public String stringX(String str) {
      String start, end, newstr="";
      if (str.length()<=1)
      return str;
      start=str.substring(0,1);
      end= str.substring(str.length()-1, str.length());
      for(int i=1; i<str.length()-1; i++){
      if(str.charAt(i)=='x')
      ;
      else
      newstr+=str.charAt(i);

      }
      return start+newstr+end;

      }

      Delete

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