File tree 4 files changed +48
-1
lines changed
4 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -51,6 +51,29 @@ isEven: true
51
51
52
52
> See [ isEven.js] ( isEven.js ) for further details.
53
53
54
+ #### isPositive
55
+
56
+ This method determines if the number provided is positive.
57
+ It is based on the fact that all positive numbers have their last
58
+ left bit to be set to 0. However, if the number provided is zero
59
+ or negative zero, it should still return false.
60
+
61
+ ``` text
62
+ Number: 1 = 0b0001
63
+ isPositive: true
64
+
65
+ Number: -1 = -0b0001
66
+ isPositive: false
67
+
68
+ Number: 0 = 0b0000
69
+ isPositive: false
70
+
71
+ Number: -0 = 0b0000
72
+ isPositive: false
73
+ ```
74
+
75
+ > See [ isPositive.js] ( isPositive.js ) for further details.
76
+
54
77
#### Multiply By Two
55
78
56
79
This method shifts original number by one bit to the left.
Original file line number Diff line number Diff line change
1
+ import isPositive from '../isPositive' ;
2
+
3
+ describe ( 'isPositive' , ( ) => {
4
+ it ( 'should detect if a number is positive' , ( ) => {
5
+ expect ( isPositive ( 0 ) ) . toBe ( false ) ;
6
+ expect ( isPositive ( - 0 ) ) . toBe ( false ) ;
7
+ expect ( isPositive ( 1 ) ) . toBe ( true ) ;
8
+ expect ( isPositive ( - 1 ) ) . toBe ( false ) ;
9
+ } ) ;
10
+ } ) ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } number
3
+ * @return {boolean }
4
+ */
5
+ export default function isPositive ( number ) {
6
+ // Zero is neither a positive nor a negative number
7
+ if ( number === 0 ) {
8
+ return false ;
9
+ }
10
+
11
+ // The most signification bit can be used to determine whether .
12
+ return ( ( number >> 31 ) & 1 ) === 0 ;
13
+ }
Original file line number Diff line number Diff line change 1
1
import multiplyByTwo from './multiplyByTwo' ;
2
2
import divideByTwo from './divideByTwo' ;
3
3
import isEven from './isEven' ;
4
+ import isPositive from './isPositive' ;
4
5
5
6
/**
6
7
* Multiply two signed numbers using bitwise operations.
@@ -34,7 +35,7 @@ export default function multiply(a, b) {
34
35
const multiplyByOddNegative = ( ) => multiply ( multiplyByTwo ( a ) , divideByTwo ( b + 1 ) ) - a ;
35
36
36
37
const multiplyByEven = ( ) => multiply ( multiplyByTwo ( a ) , divideByTwo ( b ) ) ;
37
- const multiplyByOdd = ( ) => ( b > 0 ? multiplyByOddPositive ( ) : multiplyByOddNegative ( ) ) ;
38
+ const multiplyByOdd = ( ) => ( isPositive ( b ) ? multiplyByOddPositive ( ) : multiplyByOddNegative ( ) ) ;
38
39
39
40
return isEven ( b ) ? multiplyByEven ( ) : multiplyByOdd ( ) ;
40
41
}
You can’t perform that action at this time.
0 commit comments