본문 바로가기

Coding Test/프로그래머스

[프로그래머스/자바] 짝수는 싫어요

import java.util.List;
import java.util.ArrayList;

class Solution {
    public int[] solution(int n) {
        List<Integer> list = new ArrayList<>();
        
        for(int i=1; i<=n; i+=2) {
            list.add(i);
        }
        
        int[] answer = new int[list.size()];
        for(int i=0; i<list.size(); i++) {
            answer[i] = list.get(i);
        }
        
        return answer;
    }
}

  

먼저 List에 값을 담고 int[] 배열로 옮겨 반환한다.

  


  

class Solution {
    public int[] solution(int n) {
        int size = n % 2 == 0 ? n / 2 : (n / 2 + 1);

        int[] answer = new int[size];
        
        int num = 0;
        for(int i=1; i<=n; i+=2){
            answer[num] = i;
            num++;
        }

        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();
    }
}

  

IntStream을 이용한 다른 분의 풀이