프로그래머스_짝수는 싫어요[Java]

jinoooo·2023년 3월 20일
0

프로그래머스 짝수는 싫어요

class Solution {
    public int[] solution(int n) {
    // 크기가 (n+1)/2인 배열을 생성하여 답을 저장
        int[] answer = new int[(n+1)/2];
        
        // 1부터 n까지의 숫자를 반복합니다.
        for (int i = 1 ; i <= n; i++) {
             // 숫자가 홀수인 경우
             if (i % 2 == 1 ) {
             // 답 배열의 인덱스 i/2에 추가합니다.
                  answer[i/2] = i ;
             }
         }  
        return answer;
    }
}```


람다식을 활용한 다른 분의 풀이.

import java.util.stream.IntStream;

class Solution {
public int[] solution(int n) {
return IntStream.rangeClosed(0, n).filter(value -> value % 2 == 1).toArray();
}
}

0개의 댓글