Sunday, June 5, 2016

Java Challenge - arrayFront9 - warm_up_2

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
Hisoka :
1
2
3
4
5
6
7
8
public boolean arrayFront9(int[] nums) {
  for(int i=0; i<nums.length; i++)
  {
    if (i > 3)break;
    if (nums[i] == 9) return true;
  }
  return false;
}

Hasilnya :

Codingbat:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public boolean arrayFront9(int[] nums) {
  // First figure the end for the loop
  int end = nums.length;
  if (end > 4) end = 4;
  
  for (int i=0; i<end; i++) {
    if (nums[i] == 9) return true;
  }
  
  return false;
}

No comments:

Post a Comment