fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.LinkedList;
  5. import java.util.Queue;
  6. import java.util.StringTokenizer;
  7.  
  8. public class Main {
  9. static long A;
  10. static long B;
  11. public static void main(String[] args) throws IOException {
  12. StringTokenizer st = new StringTokenizer(br.readLine());
  13. A = Long.parseLong(st.nextToken());
  14. B = Long.parseLong(st.nextToken());
  15. System.out.println(bfs(A, B));
  16. }
  17.  
  18. static int bfs(Long A, Long B) {
  19. if (A == B) { // 두 수가 같으면 1반환
  20. return 1;
  21. }
  22. Queue<Long> queue = new LinkedList<>();
  23. queue.offer(A);
  24. int count = 1;
  25. while (!queue.isEmpty()) {
  26. int size = queue.size();
  27. for (int i = 0; i < size; i++) {
  28. long num = queue.poll();
  29. long newA1 = num * 2;
  30. long newA2 = Long.parseLong(Long.toString(num) + "1");
  31.  
  32. if (newA1 == B || newA2 == B) { //정답 반환
  33. count++;
  34. return count;
  35. }
  36.  
  37. queue.offer(newA1);
  38. queue.offer(newA2);
  39. }
  40.  
  41. //queue안의 숫자들이 모두 B보다 크다면 -1 반환
  42. for (Long j : queue) {
  43. boolean check = false;
  44. if (j < B) {
  45. check = true;
  46. break;
  47. }
  48. if (!check) {
  49. return -1;
  50. }
  51. }
  52. count++;
  53. }
  54. return count;
  55. }
  56. }
  57.  
Runtime error #stdin #stdout #stderr 0.41s 143228KB
stdin
1 1000000000
stdout
Standard output is empty
stderr
Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Long.parseLong(Long.java:699)
	at java.base/java.lang.Long.parseLong(Long.java:824)
	at Main.bfs(Main.java:31)
	at Main.main(Main.java:16)