Skip to content

Commit 139efad

Browse files
committed
Counting Bits
1 parent 021e3f5 commit 139efad

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

counting-bits/sunjae95.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @description
3+
* time complexity: O(n log n)
4+
* space complexity: O(N)
5+
*
6+
* brainstorming:
7+
* convert integer to bit
8+
* for loop
9+
*
10+
* strategy:
11+
* string change to hash table
12+
*/
13+
var countBits = function (n) {
14+
return Array.from({ length: n + 1 }, (_, i) => convertBitCount(i));
15+
};
16+
17+
const convertBitCount = (n) => {
18+
let count = 0;
19+
while (n > 0) {
20+
count += n % 2;
21+
n = Math.floor(n / 2);
22+
}
23+
return count;
24+
};

0 commit comments

Comments
 (0)