/* 나누어 떨어지는 숫자 배열
* array의 각 element 중 divisor로 나누어 떨어지는 값을
* 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
* divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.
*
* arr은 자연수를 담은 배열입니다.
* 정수 i, j에 대해 i ≠ j 이면 arr[i] ≠ arr[j] 입니다.
* divisor는 자연수입니다.
* array는 길이 1 이상인 배열입니다.
*
* arr divisor return
* [5, 9, 7, 10] 5 [5, 10]
* [2, 36, 1, 3] 1 [1, 2, 3, 36]
* [3,2,6] 10 [-1]
*/
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 | import java.util.*; public class programmer_1_23 { static int[] a1 = {5, 9, 7, 10}; static int b1 = 5; static int[] a2 = {2, 36, 1, 3}; static int b2 = 1; static int[] a3 = {3, 2, 6}; static int b3 = 10; public List<Integer> solution(int[] arr, int divisor) { List<Integer> answer = new ArrayList<>(); Arrays.sort(arr); for(int i = 0; i < arr.length; i++){ if(arr[i] % divisor == 0){ answer.add(arr[i]); } } if(answer.size() == 0) answer.add(-1); return answer; } public static void main(String args[]){ programmer_1_23 t = new programmer_1_23(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(a1,b1)); System.out.println("---------------------------------------"); System.out.println("result2 = " + t.solution(a2,b2)); System.out.println("---------------------------------------"); System.out.println("result3 = " + t.solution(a3,b3)); System.out.println("---------------------------------------"); } } | cs |
'프로그래머스 > lv1' 카테고리의 다른 글
| 음양 더하기 (0) | 2022.12.14 |
|---|---|
| 제일 작은 수 제거하기 (0) | 2022.12.14 |
| 핸드폰 번호 가리기 (0) | 2022.12.14 |
| 서울에서 김서방 찾기 (0) | 2022.12.14 |
| 콜라츠 추측 (0) | 2022.12.13 |