Files
30-seconds-of-code/snippets/isPowerOfTwo.md
Angelos Chalaris 8a6b73bd0c Update covers
2023-02-16 22:24:28 +02:00

499 B

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
Number is power of two math chalarangelo flower-portrait-10 2019-12-31T13:17:12+02:00 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.
const isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
isPowerOfTwo(0); // false
isPowerOfTwo(1); // true
isPowerOfTwo(8); // true