Skip to content

Commit 3c37ba4

Browse files
committedAug 13, 2018
Add bitsDiff function.
1 parent 2361e6f commit 3c37ba4

File tree

4 files changed

+39
-25
lines changed

4 files changed

+39
-25
lines changed
 

‎src/algorithms/math/bits/README.md

+13-14
Original file line numberDiff line numberDiff line change
@@ -91,20 +91,6 @@ 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-
10894
#### Multiply Two Numbers
10995

11096
This method multiplies two integer numbers using bitwise operators.
@@ -143,6 +129,19 @@ Count of set bits = 2
143129

144130
> See `countSetBits` function for further details.
145131
132+
#### Count Bits to Flip One Number to Another
133+
134+
This methods outputs the number of bits required to convert one number to another.
135+
This makes use of property that when numbers are `XOR`-ed the result will be number
136+
of different bits.
137+
138+
```
139+
5 = 0b0101
140+
1 = 0b0001
141+
Count of Bits to be Flipped: 1
142+
```
143+
144+
> See `bitsDiff` function for further details.
146145
147146
## References
148147

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import bitsDiff from '../bitsDiff';
2+
3+
describe('bitsDiff', () => {
4+
it('should calculate bits difference between two numbers', () => {
5+
expect(bitsDiff(0, 0)).toBe(0);
6+
expect(bitsDiff(1, 1)).toBe(0);
7+
expect(bitsDiff(124, 124)).toBe(0);
8+
expect(bitsDiff(0, 1)).toBe(1);
9+
expect(bitsDiff(1, 0)).toBe(1);
10+
expect(bitsDiff(1, 2)).toBe(2);
11+
expect(bitsDiff(1, 3)).toBe(1);
12+
});
13+
});

‎src/algorithms/math/bits/bitsDiff.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import countSetBits from './countSetBits';
2+
3+
/**
4+
* Counts the number of bits that need to be change in order
5+
* to convert numberA to numberB.
6+
*
7+
* @param {number} numberA
8+
* @param {number} numberB
9+
* @return {number}
10+
*/
11+
export default function bitsDiff(numberA, numberB) {
12+
return countSetBits(numberA ^ numberB);
13+
}

‎src/algorithms/math/bits/countBitsToflipAToB.js

-11
This file was deleted.

0 commit comments

Comments
 (0)