Files
30-seconds-of-code/snippets/isPowerOfTwo.md
Isabelle Viktoria Maciohsek caa67e2a49 Update snippet descriptions
2020-10-20 23:02:01 +03:00

20 lines
375 B
Markdown

---
title: isPowerOfTwo
tags: math,beginner
---
Checks if the given number is a power of `2`.
- 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
```