Skip to content

Commit 9c1a79b

Browse files
committed
Counting Bits solution
1 parent 9a14e75 commit 9c1a79b

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

counting-bits/kimyoung.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var countBits = function (n) {
2+
let result = [];
3+
for (let i = 0; i <= n; i++) {
4+
result.push(countOneBits(i)); // count one bits for each i until n
5+
}
6+
7+
function countOneBits(num) { // method to count one bits
8+
let oneBitCount = 0;
9+
while (num) {
10+
oneBitCount += num % 2;
11+
num = num >> 1;
12+
}
13+
return oneBitCount;
14+
}
15+
16+
return result;
17+
};
18+
19+
// test cases
20+
console.log(countBits(2)); // [0,1,1]
21+
console.log(countBits(5)); // [0,1,1,2,1,2]
22+
23+
// time - O(nlogn)
24+
// space - O(n)

0 commit comments

Comments
 (0)