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