#231. Power of Two

ยท

1 min read

https://leetcode.com/problems/power-of-two/description/?envType=daily-question&envId=2024-02-19

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return n > 0 && (n & n - 1) == 0
};

To check if a number is a power of 2, it has to be greater than 0. Then we check if it's bitwise AND comparison with a number less by it by 1 returns 0, if it does then it is a power of two.

ย