Add isPowerOfTwo snippet

This commit is contained in:
Angelos Chalaris
2019-12-31 13:17:12 +02:00
parent 21b0ab5c65
commit eb55b3972a
7 changed files with 59 additions and 3 deletions

19
snippets/isPowerOfTwo.md Normal file
View File

@ -0,0 +1,19 @@
---
title: isPowerOfTwo
tags: math,beginner
---
Returns `true` if the given number is a power of `2`, `false` otherwise.
Use the bitwise binary AND operator (`&`) to determine if `n is a power of `2.
Additionally, check that `n` is not falsy.
```js
const isPowerOfTwo = n => !!n && ((n & (n - 1)) == 0);
```
```js
isPowerOfTwo(0); // false
isPowerOfTwo(1); // true
isPowerOfTwo(8); // true
```