Add bit counter function.

This commit is contained in:
Oleksii Trekhleb 2018-08-12 10:16:12 +03:00
parent a8f7d6a333
commit 9ce137cef8
3 changed files with 28 additions and 14 deletions

View File

@ -119,10 +119,12 @@ by `4` bits (`x << 4`).
#### Count Set Bits #### Count Set Bits
This method counts the number of set bits in a number using bitwise operators. 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 Number: 5 = 0b0101
Count Set Bits = 2 Count of set bits = 2
`` ``
> See `countSetBits` function for further details. > See `countSetBits` function for further details.

View File

@ -1,8 +1,15 @@
import countSetBits from '../countSetBits'; import countSetBits from '../countSetBits';
describe('countSetBits', () => { describe('countSetBits', () => {
it('Should return number of set bits', () => { it('should return number of set bits', () => {
expect(countSetBits(5)).toBe(2); expect(countSetBits(0)).toBe(0);
expect(countSetBits(1)).toBe(1); 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);
});
}); });

View File

@ -1,13 +1,18 @@
/** /**
* @param {number} number * @param {number} originalNumber
* @return {number} * @return {number}
*/ */
export default function countSetBits(number) { export default function countSetBits(originalNumber) {
let count = 0; let setBitsCount = 0;
let num = number; // eslint error https://eslint.org/docs/rules/no-param-reassign let number = originalNumber;
while (num) {
count += num & 1; while (number) {
num >>= 1; // 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;
} }