[Programmers] #120824 - 짝수 홀수 개수 [Java][C++][Python]
[Programmers] #120824 - 짝수 홀수 개수 [Java][C++][Python]
1. 아이디어
정수 배열에서 짝수의 개수와 홀수의 개수를 차례로 담아 반환하는 문제다. 모든 원소는 짝수 아니면 홀수이므로 짝수의 개수는 전체 원소 수에서 홀수의 개수를 뺀 값이고, 따라서 홀수만 세면 된다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
class Solution {
public int[] solution(int[] num_list) {
int odd = 0;
for (int x : num_list) {
if (x % 2 != 0) odd++;
}
return new int[]{num_list.length - odd, odd};
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
vector<int> solution(vector<int> num_list) {
int odd = 0;
for (int x : num_list) {
if (x % 2) odd++;
}
return {(int)num_list.size() - odd, odd};
}
1
2
3
def solution(num_list):
odd = sum(x % 2 for x in num_list)
return [len(num_list) - odd, odd]
x % 2가 홀수이면 1, 짝수이면 0이라 그 합을 홀수의 개수로 썼다.
This post is licensed under CC BY 4.0 by the author.