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

More like this

  • Number is power of ten

    Checks if the given number is a power of 10.

    JavaScript, Math · Jan 6, 2021

  • Number is negative zero

    Checks if the given value is equal to negative zero (-0).

    JavaScript, Math · Oct 20, 2020

  • Sum of powers in range

    Calculates the sum of the powers of all the numbers from start to end (both inclusive).

    JavaScript, Math · Oct 22, 2020