Add more bit manipulation functions.

This commit is contained in:
Oleksii Trekhleb
2018-06-27 17:33:16 +03:00
parent 792f4906df
commit c268203259
6 changed files with 73 additions and 1 deletions

View File

@ -49,7 +49,7 @@ a set of rules that precisely define a sequence of operations.
### Algorithms by Topic ### Algorithms by Topic
* **Math** * **Math**
* `B` [Bit Manipulation](src/algorithms/math/bits) - set/get/update/clear bits * `B` [Bit Manipulation](src/algorithms/math/bits) - set/get/update/clear bits, multiplication/division by two etc.
* `B` [Factorial](src/algorithms/math/factorial) * `B` [Factorial](src/algorithms/math/factorial)
* `B` [Fibonacci Number](src/algorithms/math/fibonacci) * `B` [Fibonacci Number](src/algorithms/math/fibonacci)
* `B` [Primality Test](src/algorithms/math/primality-test) (trial division method) * `B` [Primality Test](src/algorithms/math/primality-test) (trial division method)

View File

@ -35,3 +35,37 @@ unsets the bit.
This method is a combination of "Clear Bit" and "Set Bit" methods. This method is a combination of "Clear Bit" and "Set Bit" methods.
> See `updateBit` function for further details. > See `updateBit` function for further details.
#### Multiply By Two
This method shifts original number by one bit to the left.
Thus all binary number components (powers of two) are being
multiplying by two and thus the number itself is being
multiplied by two.
```
Before the shift
Number: 0b0101 = 5
Powers of two: 0 + 2^2 + 0 + 2^0
After the shift
Number: 0b1010 = 10
Powers of two: 2^3 + 0 + 2^1 + 0
```
#### Divide By Two
This method shifts original number by one bit to the right.
Thus all binary number components (powers of two) are being
divided by two and thus the number itself is being
divided by two without remainder.
```
Before the shift
Number: 0b0101 = 5
Powers of two: 0 + 2^2 + 0 + 2^0
After the shift
Number: 0b0010 = 2
Powers of two: 0 + 0 + 2^1 + 0
```

View File

@ -0,0 +1,12 @@
import divideByTwo from '../divideByTwo';
describe('divideByTwo', () => {
it('should divide numbers by two using bitwise operations', () => {
expect(divideByTwo(0)).toBe(0);
expect(divideByTwo(1)).toBe(0);
expect(divideByTwo(3)).toBe(1);
expect(divideByTwo(10)).toBe(5);
expect(divideByTwo(17)).toBe(8);
expect(divideByTwo(125)).toBe(62);
});
});

View File

@ -0,0 +1,12 @@
import multiplyByTwo from '../multiplyByTwo';
describe('multiplyByTwo', () => {
it('should multiply numbers by two using bitwise operations', () => {
expect(multiplyByTwo(0)).toBe(0);
expect(multiplyByTwo(1)).toBe(2);
expect(multiplyByTwo(3)).toBe(6);
expect(multiplyByTwo(10)).toBe(20);
expect(multiplyByTwo(17)).toBe(34);
expect(multiplyByTwo(125)).toBe(250);
});
});

View File

@ -0,0 +1,7 @@
/**
* @param {number} number
* @return {number}
*/
export default function divideByTwo(number) {
return number >> 1;
}

View File

@ -0,0 +1,7 @@
/**
* @param {number} number
* @return {number}
*/
export default function multiplyByTwo(number) {
return number << 1;
}