본문 바로가기

코딩테스트

짝수 홀수 개수

이지하지

 

public class NumOfNumList {
	public int[] solution(int[] num_list) {
		int[] answer = {};
		answer = new int[2];
		int a = 0; // 짝수
		int b = 0; // 홀수
		
		for(int i = 0; i < num_list.length; i++) {
			int number = num_list[i];
			
			if(number%2 == 0) { // 짝수라면
				a++;
			} else {
				b++;
			}
		}
		answer[0] = a;
		answer[1] = b;
		
		return answer;
	}
}

 

 


섹시한 코드

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[2];

        for(int i = 0; i < num_list.length; i++)
            answer[num_list[i] % 2]++;

        return answer;
    }
}

 

 

 

 

스트림1

import java.util.stream.IntStream;
import java.util.Arrays;

class Solution {
    public int[] solution(int[] numList) {
        return IntStream.of((int) Arrays.stream(numList)
        .filter(i -> i % 2 == 0).count(), (int) Arrays.stream(numList)
        .filter(i -> i % 2 == 1).count()) // IntStream
        .toArray();
    }
}

 

 

 

 

스트림2

import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int[] solution(int[] num_list) {
        return Arrays.stream(num_list)
                .boxed()
                .collect(Collectors
                         .partitioningBy(number -> number % 2 == 1, Collectors.counting()))
                .values().stream()
                .mapToInt(Long::intValue)
                .toArray();
    }
}

 

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

배열 자르기  (0) 2026.04.30
문자 반복 출력하기  (0) 2026.04.22
문자열 뒤집기  (0) 2026.04.12
배열 뒤집기  (0) 2026.04.12
나이 출력  (0) 2026.04.10