Skip to content

Instantly share code, notes, and snippets.

@aliahmadcse
Created January 29, 2021 07:14
Show Gist options
  • Save aliahmadcse/0cb574eb93aa7ad3a604f67bfdd8eeaa to your computer and use it in GitHub Desktop.
Save aliahmadcse/0cb574eb93aa7ad3a604f67bfdd8eeaa to your computer and use it in GitHub Desktop.
Given a number n. Return true if that is a power of 2.
/**
* check if N is a power of 2
* e.g, if N=8, then N is 2^3
*/
const isPowerOfTwo = (num) => {
// odd number can never be a power of two
if (num % 2 !== 0) return false;
let quotient = 0;
let chunks = [];
while (quotient !== 1) {
// quotient = 16 / 2 = 8
quotient = num / 2;
// if quotient is not even, overruling 1
if (quotient % 2 !== 0 && quotient !== 1) return false;
chunks.push(2);
num = quotient;
}
// lenght of chunks is the power of num
return chunks.length;
};
const power = isPowerOfTwo(64);
if (power) {
console.log("Given number is 2^" + power);
} else {
console.log("Number can't be raised to power of 2");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment