Skip to content

Commit e900ec9

Browse files
authored
Create BitCounting.js
1 parent f469d8c commit e900ec9

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

BitCounting.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
2+
3+
// Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
4+
5+
const countBits = function(n) {
6+
7+
return n.toString(2).split('').reduce((sum, num) => Number(sum) + Number(num), 0)
8+
9+
};
10+
11+
12+
//different approach
13+
14+
15+
countBits = n => n.toString(2).split('0').join('').length;
16+
17+
//different approach
18+
19+
const countBits = n => n.toString(2)
20+
.split('')
21+
.filter(ele => ele == 1)
22+
.length

0 commit comments

Comments
 (0)