Skip to content

Commit 9c392d7

Browse files
authored
Create 1611. Minimum One Bit Operations to Make Integers Zero 1
1 parent ef469da commit 9c392d7

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
int minimumOneBitOperations(int n) {
4+
if (n == 0) return 0;
5+
long long fun[32];
6+
// function[i] = x
7+
// Means it will take x operations to make the ith bit 1
8+
fun[0] = 1;
9+
for (int i = 1; i <= 31; i++) {
10+
fun[i] = 2 * fun[i - 1] + 1;
11+
}
12+
int res = 0;
13+
int sign = 1;
14+
for (int i = 30; i >= 0; i--) {
15+
int ithBit = (n >> i) & 1;
16+
if (ithBit == 0) continue;
17+
if (sign > 0) res += fun[i];
18+
else res -= fun[i];
19+
sign *= -1;
20+
}
21+
return res;
22+
}
23+
};

0 commit comments

Comments
 (0)