diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index 2aa672a54b..c65cbb7d84 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -53,7 +53,7 @@ isEven: true #### isPositive -This method determines if the number is positive. It is based on the fact that all positive +This method determines if the number is positive. It is based on the fact that all positive numbers have their leftmost bit to be set to `0`. However, if the number provided is zero or negative zero, it should still return `false`. @@ -226,6 +226,18 @@ Number: 9 = (10 - 1) = 0b01001 > See [isPowerOfTwo.js](isPowerOfTwo.js) for further details. +#### Bit Partitioning + +This method rewrites a number in a base which is a power of 2. +For example: + +``` +509 = 7 * ((2 ** 3) ** 2) + 7 * ((2 ** 3) ** 1) + 5 * ((2 ** 3) ** 0) +``` + +Therefore 509 (in base 10) == 775 (in base (2 ** 3)) + +> See [bitPartition.js](bitPartition.js) 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__/bitPartition.test.js b/src/algorithms/math/bits/__test__/bitPartition.test.js new file mode 100644 index 0000000000..06d993614e --- /dev/null +++ b/src/algorithms/math/bits/__test__/bitPartition.test.js @@ -0,0 +1,13 @@ +import bitPartition from '../bitPartition'; + +describe('bitPartition', () => { + it('should calculate number in a base which is a power of 2', () => { + const bits = 3; + const base = 2 ** bits; + + expect(bitPartition(0, bits)).toEqual([0]); + expect(bitPartition(base ** 0, bits)).toEqual([1]); + expect(bitPartition((base ** 3) - 1, bits)).toEqual([7, 7, 7]); + expect(bitPartition(base ** 3, bits)).toEqual([1, 0, 0, 0]); + }); +}); diff --git a/src/algorithms/math/bits/bitPartition.js b/src/algorithms/math/bits/bitPartition.js new file mode 100644 index 0000000000..9a060ef65e --- /dev/null +++ b/src/algorithms/math/bits/bitPartition.js @@ -0,0 +1,32 @@ +/** + * Return the number represented in a base which is a power of 2 + * For example given x >= 0, it can be rewritten in base 2 ** k as: + * x = xn * ((2 ** k) ** n) + ... + x0 * ((2 ** k) ** 0) + * where + * 0 <= xn, ... , x0 <= (2 ** k) - 1 + * x < (2 ** k) ** (n + 1) + * + * @param {number} number + * @param {number} number + * @return {number[]} + */ + +export default function bitPartition(num, bits) { + const mask = (1 << bits) - 1; + + // find shift + // where + // shift = n * bits + // num < (2 ** bits) ** (n + 1) + let n = 0; + while (num >= (2 ** bits) ** (n + 1)) { + n += 1; + } + + const xs = []; + for (let shift = bits * n; shift >= 0; shift -= bits) { + xs.push((num >>> shift) & mask); + } + + return xs; +}