Notice
Recent Posts
Recent Comments
Link
뮁이의 개발새발
[JAVA] 백준 16953 A → B 본문
뒤에서부터 시작하는것을 생각해보았음.. 만약 숫자가 83 이런식으로 끝자리가 1도 아니고, 짝수도 아닌 수로 나오면 어차피 시작 숫자(A)까지 도달 할 수 없으므로 불가능하다고 빼버렸다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
// 목적 숫자 B에서 출발
public class bj16953 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(in.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
int temp = B;
int cnt = 0;
while (temp != 0) {
if (temp == A) { // 시작 숫자 A가 되면 가능
System.out.println(cnt + 1);
return;
}
cnt++;
if (temp % 2 == 0) { // 짝수이면 전의 수에서 X2를 한 상태
temp = temp / 2;
} else if (temp % 10 == 1) { // 끝의 자리가 1이면 전의 수에서 +1 을 한 상태
temp = (temp - 1) / 10;
} else { // 그 외의 경우는 나올 수 없으므로 불가능
System.out.println(-1);
return;
}
}
System.out.println(-1);
}
}
Comments