Add ifPowerOf2c (#155)

This commit is contained in:
Tapasweni Pathak 2018-08-27 19:29:43 +05:30 committed by Oleksii Trekhleb
parent 20497bb044
commit 70b0e0a652
3 changed files with 33 additions and 0 deletions

View File

@ -91,6 +91,23 @@ inverting all of the bits of the number and adding 1 to it.
> See [switchSign.js](switchSign.js) for further details.
#### Power of 2
This method checks if a number provided is power of two. It uses the property that when
a power of 2 is `&` with power of 2 minus 1, it would return 0 implying that the provided
number is power of 2.
```
Number: 4
Power of 2: True
Number: 1
Power of 2: False
```
> See `ifPowerof2` function for further details.
#### Multiply Two Numbers
This method multiplies two integer numbers using bitwise operators.
@ -156,6 +173,7 @@ When we shift 1 four times it will become bigger than 5.
> See [bitLength.js](bitLength.js) for further details.
## References
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)

View File

@ -0,0 +1,8 @@
import ifPowerOf2 from '../ifPowerOf2';
describe('ifPowerOf2', () => {
it('Should return if the number is power of 2 or not', () => {
expect(ifPowerOf2(5)).toBe(false);
expect(ifPowerOf2(4)).toBe(true);
});
});

View File

@ -0,0 +1,7 @@
/**
* @param {number} number
* @return bool
*/
export default function ifPowerOf2(number) {
return number && (!(number & (number - 1)));
}