[LeetCode] Minimum Operations to Reduce an Integer to 0

2571. Minimum Operations to Reduce an Integer to 0

You are given a positive integer n, you can do the following operation any number of times:

  • Add or subtract a power of 2 from n.

Return the minimum number of operations to make n equal to 0.

A number x is power of 2 if x == 2i where i >= 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

class Solution {
public:
int minOperations(int n) {
vector<int> bit;
while(n) {
bit.push_back(n%2);
n /= 2;
}
bit.push_back(0);
bit.push_back(0);
int res = 0;
for(int i = 0, cnt = 0; i < bit.size() - 1; i++) {
if(bit[i] == 1) {
if(cnt == 0) res += 1;
cnt += 1;
} else if(bit[i] == 0) {
if(cnt == 1) cnt = 0;
else if(cnt > 1) {
res += 1;
if(bit[i+1] == 0) cnt = 0;
}
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/19/PS/LeetCode/minimum-operations-to-reduce-an-integer-to-0/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.