내 풀이
class Solution {
public int[] solution(int n, int[] numlist) {
int num = 0;
for (int j =0; j<= numlist.length-1; j++){
if(numlist[j] % n == 0) {
num++;
}
}
int k = 0;
int[] answer = new int[num];
for(int i =0; i<= numlist.length-1; i++) {
if(numlist[i] % n == 0) {
answer[k] = numlist[i];
k++;
}
}
return answer;
}
}
간단한 풀이 (Arrays 이용)
class Solution {
public int[] solution(int n, int[] numList) {
return Arrays.stream(numList).filter(value -> value % n == 0).toArray();
}
}
ArrayList 이용한 방법
import java.util.ArrayList;
class Solution {
public int[] solution(int n, int[] numlist) {
ArrayList<Integer> List = new ArrayList<>();
for(int i = 0;i < numlist.length; i++){
if(numlist[i] % n == 0){
List.add(numlist[i]);}}
int[] answer = new int[List.size()];
for(int i = 0; i< List.size(); i++){
answer[i] = List.get(i);
}
return answer;
}
}