Add bitsDiff function.

This commit is contained in:
Oleksii Trekhleb 2018-08-13 11:02:58 +03:00
parent 2361e6fc44
commit 3c37ba4424
4 changed files with 39 additions and 25 deletions

View File

@ -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

View File

@ -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);
});
});

View File

@ -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);
}

View File

@ -1,11 +0,0 @@
import countSetBits from 'countSetBits';
/**
* @param {number} number
* @return {number}
*/
export default function countBitsToflipAToB(numberA, numberB) {
return countSetBits(numberA ^ numberB);
}