Last active
March 11, 2017 16:44
-
-
Save vlad-bezden/3adba0c81766f3b0dda4227b85ff5756 to your computer and use it in GitHub Desktop.
IsPowerOfTwo
This file contains hidden or 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
'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