Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/algorithms/math/bits/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,17 @@ by `4` bits (`x << 4`).

> See `multiplyUnsigned` function for further details.

#### Count Set Bits

This method counts the number of set bits in a number using bitwise operators.

``
Number: 5 = (0101)_2
Count Set Bits = 2
``

> See `countSetBits` function for further details.

## References

- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
Expand Down
8 changes: 8 additions & 0 deletions src/algorithms/math/bits/__test__/countSetBits.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import countSetBits from '../countSetBits';

describe('countSetBits', () => {
it('Should return number of set bits', () => {
expect(countSetBits(5)).toBe(2);
expect(countSetBits(1)).toBe(1);
});
});
13 changes: 13 additions & 0 deletions src/algorithms/math/bits/countSetBits.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* @param {number} number
* @return {number}
*/
export default function countSetBits(number) {
let count = 0;
let num = number; // eslint error https://eslint.org/docs/rules/no-param-reassign
while (num) {
count += num & 1;
num >>= 1;
}
return count;
}