From a8f7d6a333f05309aa96646da7ae1cc1f1c36860 Mon Sep 17 00:00:00 2001 From: Tapasweni Pathak Date: Sun, 12 Aug 2018 12:36:13 +0530 Subject: [PATCH] Add countSetBits (#152) --- src/algorithms/math/bits/README.md | 11 +++++++++++ .../math/bits/__test__/countSetBits.test.js | 8 ++++++++ src/algorithms/math/bits/countSetBits.js | 13 +++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 src/algorithms/math/bits/__test__/countSetBits.test.js create mode 100644 src/algorithms/math/bits/countSetBits.js diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index 9c8238e5..8233567a 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -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) diff --git a/src/algorithms/math/bits/__test__/countSetBits.test.js b/src/algorithms/math/bits/__test__/countSetBits.test.js new file mode 100644 index 00000000..c204453c --- /dev/null +++ b/src/algorithms/math/bits/__test__/countSetBits.test.js @@ -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); + }); +}); diff --git a/src/algorithms/math/bits/countSetBits.js b/src/algorithms/math/bits/countSetBits.js new file mode 100644 index 00000000..d06418c6 --- /dev/null +++ b/src/algorithms/math/bits/countSetBits.js @@ -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; +}