알고리즘

백준 1107번 리모컨 (JAVA)

박카스마시며코딩 2021. 12. 13. 09:54

https://www.acmicpc.net/problem/1107

 

1107번: 리모컨

첫째 줄에 수빈이가 이동하려고 하는 채널 N (0 ≤ N ≤ 500,000)이 주어진다.  둘째 줄에는 고장난 버튼의 개수 M (0 ≤ M ≤ 10)이 주어진다. 고장난 버튼이 있는 경우에는 셋째 줄에는 고장난 버튼

www.acmicpc.net

 

이번 문제는 예외처리를 제대로 하지 않아서 계속 틀렸습니다.

첫번째 예외처리를 하지 않은 것은 0의 길이에 대한 예외처리를 하지 않았습니다. (13%정도에서 틀렸습니다.)

두번째 예외처리를 하지 않은 것은 m이 0일때 입력을 받았던 것이였습니다. (83%정도에서 null pointer)

 

 

package BOJ;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_1107 {
    static boolean broken[];
    static int cal(int target){
        int result = Math.abs(target - 100);
        for(int i = 0; i < 1_000_000 ; i++){
            int length  = check(i);
            if(length > 0){
                result = Math.min(length + Math.abs(target - i),result);
            }
        }
        return result;
    }
    static int check(int num){
        int result = 0;
        if(num == 0){
            if(broken[num]){
                return -1;
            }else{
                return 1;
            }
        }
        while(num > 0){
            if(broken[num%10]){
                return -1;
            }else{
                num /= 10;
                result++;
            }
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        int target = stoi.apply(st.nextToken());
        int m = stoi.apply(br.readLine());
        broken = new boolean[10];
        if(m != 0){
            st = new StringTokenizer(br.readLine()," ");
        }
        for(int i = 0 ; i < m ; i++){
            int temp = stoi.apply(st.nextToken());
            broken[temp] = true;
        }
        System.out.println(cal(target));
    }
}

'알고리즘' 카테고리의 다른 글

백준 1931번 회의실 배정 (JAVA)  (0) 2021.12.16
백준 1309번 동물원 (JAVA)  (0) 2021.12.14
백준 14176번 현수막 (JAVA)  (0) 2021.12.12
백준 2259번 수열 (JAVA)  (0) 2021.12.11
ALGOSPOT - BOARDCOVER(java)  (0) 2021.12.10