Files
30-seconds-of-code/snippets/isPowerOfTwo.md
30secondsofcode d51b430122 Travis build: 1670
2019-12-31 11:21:41 +00:00

20 lines
397 B
Markdown

---
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
```