/* n의 배수 고르기
* 정수 n과 정수 배열 numlist가 매개변수로 주어질 때,
* numlist에서 n의 배수가 아닌 수들을 제거한 배열을 return하도록 solution 함수를 완성해주세요.
*
* n numlist result
* 3 [4, 5, 6, 7, 8, 9, 10, 11, 12] [6, 9, 12]
* 5 [1, 9, 3, 10, 13, 5] [10, 5]
* 12 [2, 100, 120, 600, 12, 12] [120, 600, 12, 12]
*
* numlist에서 3의 배수만을 남긴 [6, 9, 12]를 return합니다.
* numlist에서 5의 배수만을 남긴 [10, 5]를 return합니다.
* numlist에서 12의 배수만을 남긴 [120, 600, 12, 12]를 return합니다.
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | public class programmer_0_14 { static int a1 = 3; static int[] ar1 = {4, 5, 6, 7, 8, 9, 10, 11, 12}; static int a2 = 5; static int[] ar2 = {1, 9, 3, 10, 13, 5}; static int a3 = 12; static int[] ar3 = {2, 100, 120, 600, 12, 12}; public int getCnt(int n, int[] numlist){ int cnt = 0; for(int i = 0; i < numlist.length; i++){ if(numlist[i]%n == 0){ cnt++; } } return cnt; } public int[] solution(int n, int[] numlist){ /* 다른사람 풀이..arraylist ArrayList<Integer> answer = new ArrayList<>(); for(int num : numlist){ if(num % n == 0){ answer.add(num); } } */ int[] answer = new int[getCnt(n,numlist)]; int cnt = 0; for(int i = 0; i < numlist.length; i++){ if(numlist[i]%n == 0){ answer[cnt] = numlist[i]; cnt++; } } return answer; } public static void main(String args[]){ programmer_0_14 t = new programmer_0_14(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(a1,ar1)); System.out.println("---------------------------------------"); // System.out.println("result2 = " + t.solution(a2,ar2)); // System.out.println("---------------------------------------"); // System.out.println("result2 = " + t.solution(a3,ar3)); // System.out.println("---------------------------------------"); } } | cs |