mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Add ifPowerOf2c (#155)
This commit is contained in:
parent
20497bb044
commit
70b0e0a652
@ -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)
|
||||
|
8
src/algorithms/math/bits/__test__/ifPowerOf2.test.js
Normal file
8
src/algorithms/math/bits/__test__/ifPowerOf2.test.js
Normal 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);
|
||||
});
|
||||
});
|
7
src/algorithms/math/bits/ifPowerOf2.js
Normal file
7
src/algorithms/math/bits/ifPowerOf2.js
Normal file
@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @param {number} number
|
||||
* @return bool
|
||||
*/
|
||||
export default function ifPowerOf2(number) {
|
||||
return number && (!(number & (number - 1)));
|
||||
}
|
Loading…
Reference in New Issue
Block a user