Files
30-seconds-of-code/snippets/is-power-of-two.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

24 lines
499 B
Markdown

---
title: Number is power of two
tags: math
author: chalarangelo
cover: flower-portrait-10
firstSeen: 2019-12-31T13:17:12+02:00
lastUpdated: 2020-10-20T23:02:01+03:00
---
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
```