Skip to content

Commit 9ce137c

Browse files
committedAug 12, 2018
Add bit counter function.
1 parent a8f7d6a commit 9ce137c

File tree

3 files changed

+28
-14
lines changed

3 files changed

+28
-14
lines changed
 

‎src/algorithms/math/bits/README.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,12 @@ by `4` bits (`x << 4`).
119119
#### Count Set Bits
120120

121121
This method counts the number of set bits in a number using bitwise operators.
122+
The main idea is that we shift the number right by one bit at a time and check
123+
the result of `&` operation that is `1` if bit is set and `0` otherwise.
122124

123125
``
124-
Number: 5 = (0101)_2
125-
Count Set Bits = 2
126+
Number: 5 = 0b0101
127+
Count of set bits = 2
126128
``
127129

128130
> See `countSetBits` function for further details.
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import countSetBits from '../countSetBits';
22

33
describe('countSetBits', () => {
4-
it('Should return number of set bits', () => {
5-
expect(countSetBits(5)).toBe(2);
6-
expect(countSetBits(1)).toBe(1);
7-
});
4+
it('should return number of set bits', () => {
5+
expect(countSetBits(0)).toBe(0);
6+
expect(countSetBits(1)).toBe(1);
7+
expect(countSetBits(2)).toBe(1);
8+
expect(countSetBits(3)).toBe(2);
9+
expect(countSetBits(4)).toBe(1);
10+
expect(countSetBits(5)).toBe(2);
11+
expect(countSetBits(21)).toBe(3);
12+
expect(countSetBits(255)).toBe(8);
13+
expect(countSetBits(1023)).toBe(10);
14+
});
815
});
+13-8
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
/**
2-
* @param {number} number
2+
* @param {number} originalNumber
33
* @return {number}
44
*/
5-
export default function countSetBits(number) {
6-
let count = 0;
7-
let num = number; // eslint error https://eslint.org/docs/rules/no-param-reassign
8-
while (num) {
9-
count += num & 1;
10-
num >>= 1;
5+
export default function countSetBits(originalNumber) {
6+
let setBitsCount = 0;
7+
let number = originalNumber;
8+
9+
while (number) {
10+
// Add last bit of the number to the sum of set bits.
11+
setBitsCount += number & 1;
12+
13+
// Shift number right by one bit to investigate other bits.
14+
number >>= 1;
1115
}
12-
return count;
16+
17+
return setBitsCount;
1318
}

0 commit comments

Comments
 (0)