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