diff --git a/README.md b/README.md index c8ec1a6d..c1cd52a1 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ a set of rules that precisely define a sequence of operations. ### Algorithms by Topic * **Math** - * `B` [Bit Manipulation](src/algorithms/math/bits) - set/get/update/clear bits, multiplication/division by two etc. + * `B` [Bit Manipulation](src/algorithms/math/bits) - set/get/update/clear bits, multiplication/division by two, make negative etc. * `B` [Factorial](src/algorithms/math/factorial) * `B` [Fibonacci Number](src/algorithms/math/fibonacci) * `B` [Primality Test](src/algorithms/math/primality-test) (trial division method) diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index 7212fdb4..736cbebf 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -53,6 +53,8 @@ Number: 0b1010 = 10 Powers of two: 2^3 + 0 + 2^1 + 0 ``` +> See `multiplyByTwo` function for further details. + #### Divide By Two This method shifts original number by one bit to the right. @@ -69,3 +71,29 @@ After the shift Number: 0b0010 = 2 Powers of two: 0 + 0 + 2^1 + 0 ``` + +> See `divideByTwo` function for further details. + +#### Switch Sign + +This method make positive numbers to be negative and backwards. +To do so it uses "Twos Complement" approach which does it by +inverting all of the bits of the number and adding 1 to it. + +``` +1101 -3 +1110 -2 +1111 -1 +0000 0 +0001 1 +0010 2 +0011 3 +``` + +> See `switchSign` function for further details. + +## References + +- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) +- [Negative Numbers in binary on YouTube](https://www.youtube.com/watch?v=4qH4unVtJkE&t=0s&index=30&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) +- [Bit Hacks on stanford.edu](https://graphics.stanford.edu/~seander/bithacks.html) diff --git a/src/algorithms/math/bits/__test__/switchSign.test.js b/src/algorithms/math/bits/__test__/switchSign.test.js new file mode 100644 index 00000000..af3f36df --- /dev/null +++ b/src/algorithms/math/bits/__test__/switchSign.test.js @@ -0,0 +1,13 @@ +import switchSign from '../switchSign'; + +describe('switchSign', () => { + it('should switch the sign of the number using twos complement approach', () => { + expect(switchSign(0)).toBe(0); + expect(switchSign(1)).toBe(-1); + expect(switchSign(-1)).toBe(1); + expect(switchSign(32)).toBe(-32); + expect(switchSign(-32)).toBe(32); + expect(switchSign(23)).toBe(-23); + expect(switchSign(-23)).toBe(23); + }); +}); diff --git a/src/algorithms/math/bits/switchSign.js b/src/algorithms/math/bits/switchSign.js new file mode 100644 index 00000000..e38ec487 --- /dev/null +++ b/src/algorithms/math/bits/switchSign.js @@ -0,0 +1,8 @@ +/** + * Switch the sign of the number using "Twos Complement" approach. + * @param {number} number + * @return {number} + */ +export default function switchSign(number) { + return ~number + 1; +}