mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Add more tests to isPositive() bitwise function.
This commit is contained in:
parent
ab7755aad7
commit
92b9e6ad1d
@ -53,10 +53,9 @@ isEven: true
|
||||
|
||||
#### isPositive
|
||||
|
||||
This method determines if the number provided is positive.
|
||||
It is based on the fact that all positive numbers have their last
|
||||
left bit to be set to 0. However, if the number provided is zero
|
||||
or negative zero, it should still return false.
|
||||
This method determines if the number is positive. It is based on the fact that all positive
|
||||
numbers have their leftmost bit to be set to `0`. However, if the number provided is zero
|
||||
or negative zero, it should still return `false`.
|
||||
|
||||
```text
|
||||
Number: 1 = 0b0001
|
||||
@ -64,12 +63,6 @@ isPositive: true
|
||||
|
||||
Number: -1 = -0b0001
|
||||
isPositive: false
|
||||
|
||||
Number: 0 = 0b0000
|
||||
isPositive: false
|
||||
|
||||
Number: -0 = 0b0000
|
||||
isPositive: false
|
||||
```
|
||||
|
||||
> See [isPositive.js](isPositive.js) for further details.
|
||||
|
@ -2,9 +2,18 @@ import isPositive from '../isPositive';
|
||||
|
||||
describe('isPositive', () => {
|
||||
it('should detect if a number is positive', () => {
|
||||
expect(isPositive(1)).toBe(true);
|
||||
expect(isPositive(2)).toBe(true);
|
||||
expect(isPositive(3)).toBe(true);
|
||||
expect(isPositive(5665)).toBe(true);
|
||||
expect(isPositive(56644325)).toBe(true);
|
||||
|
||||
expect(isPositive(0)).toBe(false);
|
||||
expect(isPositive(-0)).toBe(false);
|
||||
expect(isPositive(1)).toBe(true);
|
||||
expect(isPositive(-1)).toBe(false);
|
||||
expect(isPositive(-2)).toBe(false);
|
||||
expect(isPositive(-126)).toBe(false);
|
||||
expect(isPositive(-5665)).toBe(false);
|
||||
expect(isPositive(-56644325)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
@ -1,13 +1,13 @@
|
||||
/**
|
||||
* @param {number} number
|
||||
* @param {number} number - 32-bit integer.
|
||||
* @return {boolean}
|
||||
*/
|
||||
export default function isPositive(number) {
|
||||
// Zero is neither a positive nor a negative number
|
||||
// Zero is neither a positive nor a negative number.
|
||||
if (number === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The most signification bit can be used to determine whether .
|
||||
// The most significant 32nd bit can be used to determine whether the number is positive.
|
||||
return ((number >> 31) & 1) === 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user