Number is power of two

JavaScript, Math · Oct 20, 2020

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this