본문 바로가기

코딩테스트

짝수는 시러용

풀었다

변수를 직접 선언하면서 풀었음

 

public class Hate {
    public int[] solution(int n) {
        int[] answer = {};
        
            // 홀수라면
            if(n%2==1) {
                int a = n + 1;
                int b = a/2; // 홀수의 갯수
                int c = 1;
                answer = new int[b]; // 홀수의 갯수만큼 배열을 만듬
                for(int i = 1; i<=b; i++) {
                    if(i>=2) {
                        c = c + 2;
                        answer[i-1] = c;
                    } else { // i<2, i=1
                        c = 1;
                        answer[i-1] = c;
                    }
                }
            } else {
                int b = n/2; // 홀수의 갯수
                int c = 1;
                answer = new int[b];
                for(int i = 1; i<=b; i++) {
                    if(i>=2) {
                        c = c + 2;
                        answer[i-1] = c;
                    } else {
                        c = 1;
                        answer[i-1] = c;
                    }
                }
            }

        return answer;
    }
}

 

 

 

참고용

 

1. 어이가 없음

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

 

    public int[] solution(int n) {

        return IntStream.rangeClosed(0, n)
            .filter(e -> e % 2 != 0)
            .toArray();
    }

 

 

 

 

2. for문을 돌리는 숫자를 통해 값을 구해도 되는구나 라는걸 깨달은 코드

    public int[] solution(int n) {
        List<Integer> answer = new ArrayList<>();
        for(int i=1; i<=n; i++){
            if(i % 2 == 1){
                answer.add(i);
            }
        }
        return answer.stream().mapToInt(x -> x).toArray();
    }

 

 

 

 

 

3. 아! 배열로 반환하지 않아도 되는구나!!

    public ArrayList solution(int n) {
        ArrayList<Integer> answer = new ArrayList<Integer>();

        for(int i=1; i<=n; i++){
          if(i%2 != 0) {
              answer.add(i);
          } 
        }

        return answer;
    }

'코딩테스트' 카테고리의 다른 글

피자 나눠먹기 2  (0) 2026.03.31
피자 나눠먹기 1  (0) 2026.03.30
최빈값 구하기  (0) 2026.03.27
버블정렬 이중for문 로직 + 중앙값 구하기  (0) 2026.03.24
유클리드 호제법에 대해서  (0) 2026.03.23