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

2.34K views
0

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;
};