402 B
402 B
title, tags
| title | tags |
|---|---|
| isPowerOfTwo | math,beginner |
Returns true if the given number is a power of 2, false otherwise.
- Use the bitwise binary AND operator (
&) to determine ifnis a power of2. - Additionally, check that
nis not falsy.
const isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
isPowerOfTwo(0); // false
isPowerOfTwo(1); // true
isPowerOfTwo(8); // true