File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -49,7 +49,7 @@ a set of rules that precisely define a sequence of operations.
4949### Algorithms by Topic
5050
5151* ** Math**
52- * ` B ` [ Bit Manipulation] ( src/algorithms/math/bits ) - set/get/update/clear bits, multiplication/division by two etc.
52+ * ` B ` [ Bit Manipulation] ( src/algorithms/math/bits ) - set/get/update/clear bits, multiplication/division by two, make negative etc.
5353 * ` B ` [ Factorial] ( src/algorithms/math/factorial )
5454 * ` B ` [ Fibonacci Number] ( src/algorithms/math/fibonacci )
5555 * ` B ` [ Primality Test] ( src/algorithms/math/primality-test ) (trial division method)
Original file line number Diff line number Diff line change @@ -53,6 +53,8 @@ Number: 0b1010 = 10
5353Powers of two: 2^3 + 0 + 2^1 + 0
5454```
5555
56+ > See ` multiplyByTwo ` function for further details.
57+
5658#### Divide By Two
5759
5860This method shifts original number by one bit to the right.
@@ -69,3 +71,29 @@ After the shift
6971Number: 0b0010 = 2
7072Powers of two: 0 + 0 + 2^1 + 0
7173```
74+
75+ > See ` divideByTwo ` function for further details.
76+
77+ #### Switch Sign
78+
79+ This method make positive numbers to be negative and backwards.
80+ To do so it uses "Twos Complement" approach which does it by
81+ inverting all of the bits of the number and adding 1 to it.
82+
83+ ```
84+ 1101 -3
85+ 1110 -2
86+ 1111 -1
87+ 0000 0
88+ 0001 1
89+ 0010 2
90+ 0011 3
91+ ```
92+
93+ > See ` switchSign ` function for further details.
94+
95+ ## References
96+
97+ - [ Bit Manipulation on YouTube] ( https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8 )
98+ - [ Negative Numbers in binary on YouTube] ( https://www.youtube.com/watch?v=4qH4unVtJkE&t=0s&index=30&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8 )
99+ - [ Bit Hacks on stanford.edu] ( https://graphics.stanford.edu/~seander/bithacks.html )
Original file line number Diff line number Diff line change 1+ import switchSign from '../switchSign' ;
2+
3+ describe ( 'switchSign' , ( ) => {
4+ it ( 'should switch the sign of the number using twos complement approach' , ( ) => {
5+ expect ( switchSign ( 0 ) ) . toBe ( 0 ) ;
6+ expect ( switchSign ( 1 ) ) . toBe ( - 1 ) ;
7+ expect ( switchSign ( - 1 ) ) . toBe ( 1 ) ;
8+ expect ( switchSign ( 32 ) ) . toBe ( - 32 ) ;
9+ expect ( switchSign ( - 32 ) ) . toBe ( 32 ) ;
10+ expect ( switchSign ( 23 ) ) . toBe ( - 23 ) ;
11+ expect ( switchSign ( - 23 ) ) . toBe ( 23 ) ;
12+ } ) ;
13+ } ) ;
Original file line number Diff line number Diff line change 1+ /**
2+ * Switch the sign of the number using "Twos Complement" approach.
3+ * @param {number } number
4+ * @return {number }
5+ */
6+ export default function switchSign ( number ) {
7+ return ~ number + 1 ;
8+ }
You can’t perform that action at this time.
0 commit comments