Write a program to find if a number is power of 2 or not

3.34K viewsProgrammingprogramming
0
Answered question
1

Here is a simple solution by counting number of bits set to 1 in Javascript

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    var str = (+n.toString()).toString(2);
         var matches = str.match(/1/g);
         if (!matches || matches.length > 1 || n < 0)
        return false;
         if (matches.length === 1)
        return true;
};

Answered question
Write your answer.

Categories