문제
입력 및 출력
풀이
import java.io.*;
import java.util.*;
class Main {
public static int A;
public static int B;
public static int count;
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
A = Integer.parseInt(input[0]);
B = Integer.parseInt(input[1]);
BFS();
System.out.println(count);
}
public static void BFS() {
Queue<Integer> queue = new LinkedList<>();
queue.offer(B);
while(!queue.isEmpty()) {
int cur_number = queue.poll();
count++;
if(cur_number == A) {
break;
}
else if(cur_number < A) {
count = -1;
break;
}
if(cur_number % 2 == 0 || cur_number % 10 == 1) {
if(cur_number % 2 == 0) {
int after_number = cur_number / 2;
queue.offer(after_number);
}
else if(cur_number % 10 == 1) {
int after_number = cur_number / 10;
queue.offer(after_number);
}
}else {
count = -1;
break;
}
}
}
}
결과 및 해결방법
[결과]