Skip to content

Commit a8f7d6a

Browse files
tapaswenipathaktrekhleb
authored andcommitted
Add countSetBits (trekhleb#152)
1 parent 28ee030 commit a8f7d6a

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/algorithms/math/bits/README.md

+11
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,17 @@ by `4` bits (`x << 4`).
116116

117117
> See `multiplyUnsigned` function for further details.
118118
119+
#### Count Set Bits
120+
121+
This method counts the number of set bits in a number using bitwise operators.
122+
123+
``
124+
Number: 5 = (0101)_2
125+
Count Set Bits = 2
126+
``
127+
128+
> See `countSetBits` function for further details.
129+
119130
## References
120131

121132
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import countSetBits from '../countSetBits';
2+
3+
describe('countSetBits', () => {
4+
it('Should return number of set bits', () => {
5+
expect(countSetBits(5)).toBe(2);
6+
expect(countSetBits(1)).toBe(1);
7+
});
8+
});
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* @param {number} number
3+
* @return {number}
4+
*/
5+
export default function countSetBits(number) {
6+
let count = 0;
7+
let num = number; // eslint error https://eslint.org/docs/rules/no-param-reassign
8+
while (num) {
9+
count += num & 1;
10+
num >>= 1;
11+
}
12+
return count;
13+
}

0 commit comments

Comments
 (0)