Skip to content

Commit 2361e6f

Browse files
tapaswenipathaktrekhleb
authored andcommitted
Add countBitsToflipAToB (trekhleb#154)
1 parent 6c9641a commit 2361e6f

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

Diff for: src/algorithms/math/bits/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ inverting all of the bits of the number and adding 1 to it.
9191

9292
> See `switchSign` function for further details.
9393
94+
#### Count Bits to Flip One Number to Another
95+
96+
This methods outputs the number of bits required to convert a number to another. This
97+
makes use of property that when numbers are XORed the result will be number of different
98+
bits and `countSetBits`.
99+
100+
``
101+
Number A : 5 = (0101)_2
102+
Number B : 1 = (0001)_2
103+
Count Bits to be Flipped: 1
104+
``
105+
106+
> See `countBitsToflipAToB` function for further details.
107+
94108
#### Multiply Two Numbers
95109

96110
This method multiplies two integer numbers using bitwise operators.
@@ -129,6 +143,7 @@ Count of set bits = 2
129143

130144
> See `countSetBits` function for further details.
131145
146+
132147
## References
133148

134149
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

Diff for: src/algorithms/math/bits/countBitsToflipAToB.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import countSetBits from 'countSetBits';
2+
3+
/**
4+
* @param {number} number
5+
* @return {number}
6+
*/
7+
export default function countBitsToflipAToB(numberA, numberB) {
8+
9+
return countSetBits(numberA ^ numberB);
10+
11+
}

0 commit comments

Comments
 (0)