From 9111568fc02f16c881b5fd83337b461461c5769a Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Mon, 13 Aug 2018 18:06:48 +0300 Subject: [PATCH] Add bits counter function. --- src/algorithms/math/bits/README.md | 13 +++++++++++++ .../math/bits/__test__/bitLength.test.js | 14 ++++++++++++++ src/algorithms/math/bits/bitLength.js | 15 +++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 src/algorithms/math/bits/__test__/bitLength.test.js create mode 100644 src/algorithms/math/bits/bitLength.js diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index 21ef97ec..7570e7bd 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -143,6 +143,19 @@ Count of Bits to be Flipped: 1 > 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 - [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) diff --git a/src/algorithms/math/bits/__test__/bitLength.test.js b/src/algorithms/math/bits/__test__/bitLength.test.js new file mode 100644 index 00000000..1731b568 --- /dev/null +++ b/src/algorithms/math/bits/__test__/bitLength.test.js @@ -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); + }); +}); diff --git a/src/algorithms/math/bits/bitLength.js b/src/algorithms/math/bits/bitLength.js new file mode 100644 index 00000000..0fc2727d --- /dev/null +++ b/src/algorithms/math/bits/bitLength.js @@ -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; +}