Post

[Programmers] #120905 - n의 배수 고르기 [Java][C++][Python]

[Programmers] #120905 - n의 배수 고르기 [Java][C++][Python]

문제 링크


1. 아이디어

배열에서 $n$의 배수만 남기는 문제다. 원소마다 $n$으로 나눈 나머지가 0인지만 보고 앞에서부터 걸러 내면 원래 순서가 그대로 유지된다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
import java.util.*;

class Solution {
    public int[] solution(int n, int[] numlist) {
        return Arrays.stream(numlist).filter(x -> x % n == 0).toArray();
    }
}

Arrays.stream으로 만든 IntStream에서 filter로 조건이 참인 원소만 남겼다. IntStream은 기본형 스트림이라 toArray가 int[]를 그대로 돌려준다.

1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(int n, vector<int> numlist) {
    vector<int> v;
    for (int x : numlist) {
        if (x % n == 0) v.push_back(x);
    }

    return v;
}
1
2
def solution(n, numlist):
    return [x for x in numlist if x % n == 0]

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