Add bits counter function.

This commit is contained in:
Oleksii Trekhleb 2018-08-13 18:06:48 +03:00
parent 3c37ba4424
commit 9111568fc0
3 changed files with 42 additions and 0 deletions

View File

@ -143,6 +143,19 @@ Count of Bits to be Flipped: 1
> See `bitsDiff` function for further details. > See `bitsDiff` function for further details.
#### Count Bits of a Number
To calculate the number of valuable bits we need to shift `1` one bit left each
time and see if shifted number is bigger than the input number.
```
5 = 0b0101
Count of valuable bits is: 3
When we shift 1 four times it will become bigger than 5.
```
> See `bitsDiff` function for further details.
## References ## References
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) - [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

View File

@ -0,0 +1,14 @@
import bitLength from '../bitLength';
describe('bitLength', () => {
it('should calculate number of bits that the number is consists of', () => {
expect(bitLength(0b0)).toBe(0);
expect(bitLength(0b1)).toBe(1);
expect(bitLength(0b01)).toBe(1);
expect(bitLength(0b101)).toBe(3);
expect(bitLength(0b0101)).toBe(3);
expect(bitLength(0b10101)).toBe(5);
expect(bitLength(0b11110101)).toBe(8);
expect(bitLength(0b00011110101)).toBe(8);
});
});

View File

@ -0,0 +1,15 @@
/**
* Return the number of bits used in the binary representation of the number.
*
* @param {number} number
* @return {number}
*/
export default function bitLength(number) {
let bitsCounter = 0;
while ((1 << bitsCounter) <= number) {
bitsCounter += 1;
}
return bitsCounter;
}