Post

짝수 홀수 개수

📃 문제

image


🔨 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = {0,0};
        
        for(int i=0; i<num_list.length ; i++){
            int num = num_list[i];
            if(num %2 ==0) answer[0]+=1;
            else answer[1]+=1;
        }
        
        return answer;
    }
}

짝수 홀수의 개수를 담을 answer 배열을 선언한다.

for반복문을 통해 매개변수 num_list의 배열 길이까지 반복식을 만든다.

현재 숫자를 num_list에서 가져옵니다.

num이 짝수 인지 확인하고 짝수인 경우, ‘answer’ 배열의 첫 번째 요소를 증가시킵니다.

num이 홀 수 인경우, answer’ 배열의 두 번째 요소를 증가시킵니다.

This post is licensed under CC BY 4.0 by the author.