Skip to content

Commit ab7755a

Browse files
adityahirantrekhleb
authored andcommittedSep 14, 2018
feat(bitwise): Function to check if a number is positive (trekhleb#204)
1 parent 861e0e9 commit ab7755a

File tree

4 files changed

+48
-1
lines changed

4 files changed

+48
-1
lines changed
 

‎src/algorithms/math/bits/README.md

+23
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,29 @@ isEven: true
5151

5252
> See [isEven.js](isEven.js) for further details.
5353
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+
5477
#### Multiply By Two
5578

5679
This method shifts original number by one bit to the left.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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+
});
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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+
}

‎src/algorithms/math/bits/multiply.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import multiplyByTwo from './multiplyByTwo';
22
import divideByTwo from './divideByTwo';
33
import isEven from './isEven';
4+
import isPositive from './isPositive';
45

56
/**
67
* Multiply two signed numbers using bitwise operations.
@@ -34,7 +35,7 @@ export default function multiply(a, b) {
3435
const multiplyByOddNegative = () => multiply(multiplyByTwo(a), divideByTwo(b + 1)) - a;
3536

3637
const multiplyByEven = () => multiply(multiplyByTwo(a), divideByTwo(b));
37-
const multiplyByOdd = () => (b > 0 ? multiplyByOddPositive() : multiplyByOddNegative());
38+
const multiplyByOdd = () => (isPositive(b) ? multiplyByOddPositive() : multiplyByOddNegative());
3839

3940
return isEven(b) ? multiplyByEven() : multiplyByOdd();
4041
}

0 commit comments

Comments
 (0)
Please sign in to comment.