mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
Add bit counter function.
This commit is contained in:
parent
a8f7d6a333
commit
9ce137cef8
@ -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.
|
||||||
|
@ -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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
@ -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;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user