Skip to content

Commit f6ca055

Browse files
authored
Create least-operators-to-express-number.py
1 parent 4dc311a commit f6ca055

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Time: O(logn) = O(32) = O(1)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def leastOpsExpressTarget(self, x, target):
6+
"""
7+
:type x: int
8+
:type target: int
9+
:rtype: int
10+
"""
11+
pos, neg, k = 0, 0, 0
12+
while target:
13+
target, r = divmod(target, x)
14+
if k:
15+
pos, neg = min(r*k + pos, (r+1)*k + neg), \
16+
min((x-r)*k + pos, (x-r-1)*k + neg)
17+
else:
18+
pos, neg = r*2, (x-r)*2
19+
k += 1
20+
return min(pos, k+neg) - 1

0 commit comments

Comments
 (0)