Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2663bb8

Browse files
991 Broken Calculator.py
1 parentb713f7a commit2663bb8

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

‎991 Broken Calculator.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/python3
2+
"""
3+
On a broken calculator that has a number showing on its display, we can perform
4+
two operations:
5+
6+
Double: Multiply the number on the display by 2, or;
7+
Decrement: Subtract 1 from the number on the display.
8+
Initially, the calculator is displaying the number X.
9+
10+
Return the minimum number of operations needed to display the number Y.
11+
12+
13+
14+
Example 1:
15+
16+
Input: X = 2, Y = 3
17+
Output: 2
18+
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
19+
Example 2:
20+
21+
Input: X = 5, Y = 8
22+
Output: 2
23+
Explanation: Use decrement and then double {5 -> 4 -> 8}.
24+
Example 3:
25+
26+
Input: X = 3, Y = 10
27+
Output: 3
28+
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
29+
Example 4:
30+
31+
Input: X = 1024, Y = 1
32+
Output: 1023
33+
Explanation: Use decrement operations 1023 times.
34+
35+
36+
Note:
37+
38+
1 <= X <= 10^9
39+
1 <= Y <= 10^9
40+
"""
41+
42+
43+
classSolution:
44+
defbrokenCalc(self,X:int,Y:int)->int:
45+
"""
46+
greedy + work backward
47+
48+
If Y is odd, we can do only Y = Y + 1
49+
If Y is even, if we plus 1 to Y, then Y is odd, we need to plus another 1.
50+
And because (Y + 1 + 1) / 2 = (Y / 2) + 1, 3 operations are more than 2.
51+
We always choose Y / 2 if Y is even.
52+
"""
53+
t=0
54+
whileY>X:
55+
ifY%2==0:
56+
Y//=2
57+
else:
58+
Y+=1
59+
t+=1
60+
61+
returnt+X-Y
62+
63+
defbrokenCalc_TLE(self,X:int,Y:int)->int:
64+
"""
65+
BFS
66+
"""
67+
q= [X]
68+
t=0
69+
has_larger=False
70+
whileq:
71+
cur_q= []
72+
foreinq:
73+
ife==Y:
74+
returnt
75+
76+
cur=e*2
77+
ifcur>=1:
78+
ifcur>Yandnothas_larger:
79+
has_larger=True
80+
cur_q.append(cur)
81+
elifcur<=Y:
82+
cur_q.append(cur)
83+
84+
cur=e-1
85+
ifcur>=1:
86+
cur_q.append(cur)
87+
q=cur_q
88+
t+=1
89+
90+
raise
91+
92+
93+
if__name__=="__main__":
94+
assertSolution().brokenCalc(2,3)==2

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp