/* 가까운 수
* 정수 배열 array와 정수 n이 매개변수로 주어질 때,
* array에 들어있는 정수 중 n과 가장 가까운 수를 return
*
* 1 ≤ array 원소, n ≤ 100
* 가장 가까운 수가 여러 개일 경우 더 작은 수를 return 합니다.
*
* array n result
* [3, 10, 28] 20 28 3, 10, 28 중 20과 가장 가까운 수는 28
* [10, 11, 12] 13 12 10, 11, 12 중 13과 가장 가까운 수는 12
*/
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 | import java.util.*; import java.lang.*; public class programmer_0_27 { static int[] ar1 = {3,10,12,28}; static int a1 = 20; static int[] ar2 = {10,11,12}; static int a2 = 13; public int solution(int[] array, int n) { int answer = 0; int gap = 0; int idx = 0; for(int i = 0; i < array.length; i++){ if(i == 0){ gap = Math.abs(n - array[i]); idx = i; } else if(gap > Math.abs(n - array[i])){ gap = Math.abs(n - array[i]); //절대값 idx = i; } else if(gap == Math.abs(n - array[i])){ if(array[idx] > array[i]) idx = i; } } answer = array[idx]; return answer; } public static void main(String args[]){ programmer_0_27 t = new programmer_0_27(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(ar1,a1)); System.out.println("---------------------------------------"); // System.out.println("result2 = " + t.solution(ar2,a2)); // System.out.println("---------------------------------------"); } } | cs |