Last active
June 8, 2020 07:42
-
-
Save RP-3/9385121c6da0b42831781d3ea5d7ec26 to your computer and use it in GitHub Desktop.
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
/** | |
* @param {number} n | |
* @return {boolean} | |
*/ | |
// Idea: if it's a power of two, there must | |
// be only one bit set. | |
var isPowerOfTwo = function(n) { | |
if(n<=0) return false; // it could be negative. Return false; | |
n&=(n-1); // unset the lowest set bit | |
return n === 0; // If there are any bits left, return false. Otherwise | |
// it's a power of two! | |
}; | |
// turned into golf because why not... | |
var golf = (n) => n<=0 ? false : (n&(n-1)) === 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment