Skip to content

Commit a533c6a

Browse files
authored
Create 2571-minimum-operations-to-reduce-an-integer-to-0.js
1 parent 40d34be commit a533c6a

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function dec2bin(dec) {
2+
return (dec >>> 0).toString(2);
3+
}
4+
function bitCnt(s) {
5+
let res = 0
6+
for(const e of s) {
7+
if(e === '1') res++
8+
}
9+
return res
10+
}
11+
/**
12+
* @param {number} n
13+
* @return {number}
14+
*/
15+
var minOperations = function(n) {
16+
if(n === 0) return 0
17+
if(bitCnt(dec2bin(n)) === 1) return 1
18+
const lowBit = n & -n
19+
let low = minOperations(n + lowBit);
20+
let high = minOperations(n - lowBit);
21+
return Math.min(low, high) + 1;
22+
};

0 commit comments

Comments
 (0)