Skip to content

Commit fa8b1b5

Browse files
committed
[level 2] Title: 숫자 변환하기, Time: 306.16 ms, Memory: 37.7 MB -BaekjoonHub
1 parent b17d775 commit fa8b1b5

2 files changed

Lines changed: 108 additions & 0 deletions

File tree

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# [level 2] 숫자 변환하기 - 154538
2+
3+
[문제 링크](https://school.programmers.co.kr/learn/courses/30/lessons/154538)
4+
5+
### 성능 요약
6+
7+
메모리: 37.7 MB, 시간: 306.16 ms
8+
9+
### 구분
10+
11+
코딩테스트 연습 > 연습문제
12+
13+
### 채점결과
14+
15+
정확성: 100.0<br/>합계: 100.0 / 100.0
16+
17+
### 제출 일자
18+
19+
2026년 02월 02일 15:11:57
20+
21+
### 문제 설명
22+
23+
<p>자연수 <code>x</code>를 <code>y</code>로 변환하려고 합니다. 사용할 수 있는 연산은 다음과 같습니다.</p>
24+
25+
<ul>
26+
<li><code>x</code>에 <code>n</code>을 더합니다</li>
27+
<li><code>x</code>에 2를 곱합니다.</li>
28+
<li><code>x</code>에 3을 곱합니다.</li>
29+
</ul>
30+
31+
<p>자연수 <code>x</code>, <code>y</code>, <code>n</code>이 매개변수로 주어질 때, <code>x</code>를 <code>y</code>로 변환하기 위해 필요한 최소 연산 횟수를 return하도록 solution 함수를 완성해주세요. 이때 <code>x</code>를 <code>y</code>로 만들 수 없다면 -1을 return 해주세요.</p>
32+
33+
<hr>
34+
35+
<h5>제한사항</h5>
36+
37+
<ul>
38+
<li>1&nbsp;&nbsp;<code>x</code> ≤ <code>y</code>&nbsp;≤ 1,000,000</li>
39+
<li>1 ≤ <code>n</code> &lt; <code>y</code></li>
40+
</ul>
41+
42+
<hr>
43+
44+
<h5>입출력 예</h5>
45+
<table class="table">
46+
<thead><tr>
47+
<th>x</th>
48+
<th>y</th>
49+
<th>n</th>
50+
<th>result</th>
51+
</tr>
52+
</thead>
53+
<tbody><tr>
54+
<td>10</td>
55+
<td>40</td>
56+
<td>5</td>
57+
<td>2</td>
58+
</tr>
59+
<tr>
60+
<td>10</td>
61+
<td>40</td>
62+
<td>30</td>
63+
<td>1</td>
64+
</tr>
65+
<tr>
66+
<td>2</td>
67+
<td>5</td>
68+
<td>4</td>
69+
<td>-1</td>
70+
</tr>
71+
</tbody>
72+
</table>
73+
<hr>
74+
75+
<h5>입출력 예 설명</h5>
76+
77+
<p>입출력 예 #1<br>
78+
<code>x</code>에 2를 2번 곱하면 40이 되고 이때가 최소 횟수입니다.</p>
79+
80+
<p>입출력 예 #2<br>
81+
<code>x</code>에 <code>n</code>인 30을 1번 더하면 40이 되고 이때가 최소 횟수입니다.</p>
82+
83+
<p>입출력 예 #3<br>
84+
<code>x</code>를 <code>y</code>로 변환할 수 없기 때문에 -1을 return합니다.</p>
85+
86+
87+
> 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from collections import deque
2+
3+
def solution(x, y, n):
4+
q = deque([(x, 0)])
5+
visited = [False] * 1000001
6+
while q:
7+
now, cnt = q.popleft()
8+
if now == y:
9+
return cnt
10+
11+
if now + n <= y and not visited[now+n]:
12+
q.append((now + n, cnt + 1))
13+
visited[now+n] = True
14+
if now * 2 <= y and not visited[now*2]:
15+
q.append((now * 2, cnt + 1))
16+
visited[now*2] = True
17+
if now * 3 <= y and not visited[now*3]:
18+
q.append((now * 3, cnt + 1))
19+
visited[now*3] = True
20+
21+
return -1

0 commit comments

Comments
 (0)