Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active March 11, 2017 16:44
Show Gist options
  • Save vlad-bezden/3adba0c81766f3b0dda4227b85ff5756 to your computer and use it in GitHub Desktop.
Save vlad-bezden/3adba0c81766f3b0dda4227b85ff5756 to your computer and use it in GitHub Desktop.
IsPowerOfTwo
'use strcit'
/*
* Calculate if number is power of two. For instance 1, 2, 4, 8, 16, 32, 64, 128, ...
*
* @param {Number} n - number > 0
* @returns {Bool} - true if number is power of two false otherwise
*/
function isPowerOfTwo(n) {
if (n < 0) {
return Number.NaN
} else if (n === 0) {
return Number.NEGATIVE_INFINITY
} else if (n === 1 || n === 2) {
return true
} else if (n % 2 > 0) {
return false
}
return isPowerOfTwo(n >>> 1)
}
[...Array(100)].forEach((_, i) => (i, console.log(i, isPowerOfTwo(i))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment