DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

 

Power of Two - LeetCode

Given an integer, write a function to determine if it is a power of two.

Algorithm:

The intuition here is compare all the 2 ^ i values with n. If they are equal return true else if 2 ^ i is greater than n then return false

Code:

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    let cur = 0
    let temp = 1
    while(temp <= n) {
        if(temp == n) {
            return true
        }
        temp = Math.pow(2, cur);
        cur++
    }

    return false
};

Alternative ways:

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return Math.log2(n)%1 === 0
};
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return n < 1 ? false : Number.MAX_VALUE % n == 0
};

Latest comments (1)

Collapse
 
ravi1512 profile image
Ravi Mishra

There's an interesting bit property that we can use to solve this. If you AND a number with number - 1, and it's 0 then it is a power of 2. Binary representation of any number which is a power of 2 will have only one set bit and the number less than that will have all bits set except the left most bit. Take 32 for example
32 - 100000
31 - 011111
32 & 31 - 000000

This property won't hold true for numbers which aren't power of 2.

An Animated Guide to Node.js Event Loop

Node.js doesnโ€™t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.