Skip to content

Commit

Permalink
Add bitsDiff function.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Aug 13, 2018
1 parent 2361e6f commit 3c37ba4
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 25 deletions.
27 changes: 13 additions & 14 deletions src/algorithms/math/bits/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions src/algorithms/math/bits/__test__/bitsDiff.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
13 changes: 13 additions & 0 deletions src/algorithms/math/bits/bitsDiff.js
Original file line number Diff line number Diff line change
@@ -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);
}
11 changes: 0 additions & 11 deletions src/algorithms/math/bits/countBitsToflipAToB.js

This file was deleted.

0 comments on commit 3c37ba4

Please sign in to comment.