카테고리 없음

[programmers] JAVA_0단계 짝수는 싫어요

congs 2024. 6. 20. 23:45

짝수는 싫어요

 

풀이

- idx를 이용하여 for문으로 배열을 채우는 방법

class Solution {
    public int[] solution(int n) {
        
        int[] answer = new int[(n + 1) / 2];
        int idx = 0;
        
        for(int i = 1; i <= n; i+= 2){
            answer[idx] = i;
            idx++;  
        }
        
        return answer;
    }
}

 

- ⭐ IntStream을 이용하는 방법

import java.util.stream.IntStream;

class Solution {
    public int[] solution(int n) {

        return IntStream.rangeClosed(0, n)
            .filter(e -> e % 2 != 0)
            .toArray();
    }
}
  • IntStream.rangeClosed(0,n) : 0부터 n까지 포함된 정수 스트림을 생성
  • filter( e -> e % 2 != 0) : 주어진 조건에 맞는 요소만을 포함! 2로 나누었을때 나머지가 있는 것이 조건
  • toArray() : 스트림의 요소들을 배열로 전환