Add countSetBits (#152)

This commit is contained in:
Tapasweni Pathak 2018-08-12 12:36:13 +05:30 committed by Oleksii Trekhleb
parent 28ee030a82
commit a8f7d6a333
3 changed files with 32 additions and 0 deletions

View File

@ -116,6 +116,17 @@ by `4` bits (`x << 4`).
> See `multiplyUnsigned` function for further details. > 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 ## References
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) - [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

View File

@ -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);
});
});

View File

@ -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;
}