[Algorithm Study] 백준 16953

SeokHwan An·2022년 3월 13일
0

문제 출처 : https://www.acmicpc.net/problem/16953

문제 접근

위의 문제의 경우 A에서 B로 가는 형태가 아닌 B에서 A로 가는 방식으로 문제에 접근했습니다. 즉 B가 2로 나누어지는 경우에는 2로 나누었고 B의 1의자리 숫자가 1인 경우에는 1을 제거했습니다. 이를 코드로 작성하면 다음과 같습니다.

소스 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        int A = Integer.parseInt(st.nextToken());
        int B = Integer.parseInt(st.nextToken());
        int cnt = 0;
        while(B > A){
            if(B % 2 == 0){ //B가 2로 나누어지는 경우
                cnt++;
                B /= 2;
            }
            else{
                String b = String.valueOf(B);
                if(b.charAt(b.length()-1) == '1'){
                    b = b.substring(0,b.length()-1);
                    cnt++;
                    B = Integer.parseInt(b);
                }
                else{
                    break;
                }
            }
        }
        if(A == B){
            System.out.println(cnt+1);
        }
        else{
            System.out.println(-1);
        }
    }
}

0개의 댓글