diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index afffc160..ef6ad311 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -91,6 +91,20 @@ 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. @@ -129,6 +143,7 @@ Count of set bits = 2 > See `countSetBits` 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/countBitsToflipAToB.js b/src/algorithms/math/bits/countBitsToflipAToB.js new file mode 100644 index 00000000..cc86883d --- /dev/null +++ b/src/algorithms/math/bits/countBitsToflipAToB.js @@ -0,0 +1,11 @@ +import countSetBits from 'countSetBits'; + +/** + * @param {number} number + * @return {number} + */ +export default function countBitsToflipAToB(numberA, numberB) { + + return countSetBits(numberA ^ numberB); + +}