diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index ef6ad311..21ef97ec 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -91,20 +91,6 @@ inverting all of the bits of the number and adding 1 to it. > See `switchSign` function for further details. -#### Count Bits to Flip One Number to Another - -This methods outputs the number of bits required to convert a number to another. This -makes use of property that when numbers are XORed the result will be number of different -bits and `countSetBits`. - -`` -Number A : 5 = (0101)_2 -Number B : 1 = (0001)_2 -Count Bits to be Flipped: 1 -`` - -> See `countBitsToflipAToB` function for further details. - #### Multiply Two Numbers This method multiplies two integer numbers using bitwise operators. @@ -143,6 +129,19 @@ Count of set bits = 2 > See `countSetBits` function for further details. +#### Count Bits to Flip One Number to Another + +This methods outputs the number of bits required to convert one number to another. +This makes use of property that when numbers are `XOR`-ed the result will be number +of different bits. + +``` +5 = 0b0101 +1 = 0b0001 +Count of Bits to be Flipped: 1 +``` + +> See `bitsDiff` function for further details. ## References diff --git a/src/algorithms/math/bits/__test__/bitsDiff.test.js b/src/algorithms/math/bits/__test__/bitsDiff.test.js new file mode 100644 index 00000000..e1fd6416 --- /dev/null +++ b/src/algorithms/math/bits/__test__/bitsDiff.test.js @@ -0,0 +1,13 @@ +import bitsDiff from '../bitsDiff'; + +describe('bitsDiff', () => { + it('should calculate bits difference between two numbers', () => { + expect(bitsDiff(0, 0)).toBe(0); + expect(bitsDiff(1, 1)).toBe(0); + expect(bitsDiff(124, 124)).toBe(0); + expect(bitsDiff(0, 1)).toBe(1); + expect(bitsDiff(1, 0)).toBe(1); + expect(bitsDiff(1, 2)).toBe(2); + expect(bitsDiff(1, 3)).toBe(1); + }); +}); diff --git a/src/algorithms/math/bits/bitsDiff.js b/src/algorithms/math/bits/bitsDiff.js new file mode 100644 index 00000000..dbb77b89 --- /dev/null +++ b/src/algorithms/math/bits/bitsDiff.js @@ -0,0 +1,13 @@ +import countSetBits from './countSetBits'; + +/** + * Counts the number of bits that need to be change in order + * to convert numberA to numberB. + * + * @param {number} numberA + * @param {number} numberB + * @return {number} + */ +export default function bitsDiff(numberA, numberB) { + return countSetBits(numberA ^ numberB); +} diff --git a/src/algorithms/math/bits/countBitsToflipAToB.js b/src/algorithms/math/bits/countBitsToflipAToB.js deleted file mode 100644 index cc86883d..00000000 --- a/src/algorithms/math/bits/countBitsToflipAToB.js +++ /dev/null @@ -1,11 +0,0 @@ -import countSetBits from 'countSetBits'; - -/** - * @param {number} number - * @return {number} - */ -export default function countBitsToflipAToB(numberA, numberB) { - - return countSetBits(numberA ^ numberB); - -}