본문 바로가기

Chapter01/고딩데스드

[고딩데스드] 짝수는 싫어요

코딩테스트 연습 > 코딩테스트 입문 > 짝수는 싫어요

짝수는 싫어요

문제 설명
정수 n이 매개변수로 주어질 때, n 이하의 홀수가 오름차순으로 담긴 배열을 return하도록 solution 함수를 완성해주세요.

제한사항
1 ≤ n ≤ 100

입출력 예

n result
10 [ 1, 3, 5, 7, 9]
15 [1, 3, 5, 7, 9, 11, 13, 15]

 

class Solution {
    public int[] solution(int n) {
        int length = (n + 1) / 2;
        int[] result = new int[length];
        int odd = 1; 

        for (int i = 0; i < length; i++) {
            result[i] = odd;
            odd += 2; 
        }
        return result;
    }
}

 

다른 사람의 풀이

 

import java.util.stream.IntStream;

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

 

나 스트림 잘 모르는데,, 공부해야겠다