본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 2단계 : arrayFront9 문제

728x90
728x90

https://codingbat.com/prob/p186031

 

CodingBat Java Warmup-2 arrayFront9

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]) → truearrayFront9([1, 2, 3, 4, 9]) → falsearrayFront9([1, 2, 3, 4, 5]) → falseGo...Save, Compile,

codingbat.com



= 문제 번역 =

int 배열이 주어지면 배열의 4번째까지의 요소 중의 하나가 9이면 true를 반환합니다.

배열 길이는 4보다 작을 수 있습니다.

 

= 문제푸는 팁 =

제일 큰 조건은 배열이 4보다 작으면서,

i가 ==9가 아닐 때, i가 하나씩 커지게하면서, i가 차츰올라가면서 9가있다면 true반환하게 하면 된다,

4 이후의 숫자는 따지지 않는 것이 중요하다.

 

= 해설 =

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

< 2 >
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;
}

728x90