Created
January 29, 2021 07:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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