mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 07:01:18 +08:00
Add countSetBits (#152)
This commit is contained in:
parent
28ee030a82
commit
a8f7d6a333
@ -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)
|
||||
|
8
src/algorithms/math/bits/__test__/countSetBits.test.js
Normal file
8
src/algorithms/math/bits/__test__/countSetBits.test.js
Normal 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);
|
||||
});
|
||||
});
|
13
src/algorithms/math/bits/countSetBits.js
Normal file
13
src/algorithms/math/bits/countSetBits.js
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user