Skip to content

Commit 4dc311a

Browse files
authored
Create least-operators-to-express-number.cpp
1 parent 8e25aa6 commit 4dc311a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(logn) = O(32) = O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int leastOpsExpressTarget(int x, int target) {
7+
int pos = 0, neg = 0, k;
8+
for (k = 0; target > 0; ++k, target /= x) {
9+
int r = target % x;
10+
if (k > 0) {
11+
tie(pos, neg) = make_pair(
12+
min(r * k + pos, (r + 1) * k + neg),
13+
min((x - r) * k + pos, (x - r - 1) * k + neg)
14+
);
15+
} else {
16+
tie(pos, neg) = make_pair(r * 2, (x - r) * 2);
17+
}
18+
}
19+
return min(pos, k + neg) - 1;
20+
}
21+
};

0 commit comments

Comments
 (0)