From 9ce137cef86a634acd83eab3a872e652243d93d5 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Sun, 12 Aug 2018 10:16:12 +0300 Subject: [PATCH] Add bit counter function. --- src/algorithms/math/bits/README.md | 6 ++++-- .../math/bits/__test__/countSetBits.test.js | 15 +++++++++---- src/algorithms/math/bits/countSetBits.js | 21 ++++++++++++------- 3 files changed, 28 insertions(+), 14 deletions(-) diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index 8233567a..c8ac92b4 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -119,10 +119,12 @@ by `4` bits (`x << 4`). #### Count Set Bits This method counts the number of set bits in a number using bitwise operators. +The main idea is that we shift the number right by one bit at a time and check +the result of `&` operation that is `1` if bit is set and `0` otherwise. `` -Number: 5 = (0101)_2 -Count Set Bits = 2 +Number: 5 = 0b0101 +Count of set bits = 2 `` > See `countSetBits` function for further details. diff --git a/src/algorithms/math/bits/__test__/countSetBits.test.js b/src/algorithms/math/bits/__test__/countSetBits.test.js index c204453c..fb29cb09 100644 --- a/src/algorithms/math/bits/__test__/countSetBits.test.js +++ b/src/algorithms/math/bits/__test__/countSetBits.test.js @@ -1,8 +1,15 @@ import countSetBits from '../countSetBits'; describe('countSetBits', () => { - it('Should return number of set bits', () => { - expect(countSetBits(5)).toBe(2); - expect(countSetBits(1)).toBe(1); - }); + it('should return number of set bits', () => { + expect(countSetBits(0)).toBe(0); + expect(countSetBits(1)).toBe(1); + expect(countSetBits(2)).toBe(1); + expect(countSetBits(3)).toBe(2); + expect(countSetBits(4)).toBe(1); + expect(countSetBits(5)).toBe(2); + expect(countSetBits(21)).toBe(3); + expect(countSetBits(255)).toBe(8); + expect(countSetBits(1023)).toBe(10); + }); }); diff --git a/src/algorithms/math/bits/countSetBits.js b/src/algorithms/math/bits/countSetBits.js index d06418c6..6e24eebf 100644 --- a/src/algorithms/math/bits/countSetBits.js +++ b/src/algorithms/math/bits/countSetBits.js @@ -1,13 +1,18 @@ /** - * @param {number} number + * @param {number} originalNumber * @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; +export default function countSetBits(originalNumber) { + let setBitsCount = 0; + let number = originalNumber; + + while (number) { + // Add last bit of the number to the sum of set bits. + setBitsCount += number & 1; + + // Shift number right by one bit to investigate other bits. + number >>= 1; } - return count; + + return setBitsCount; }