Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active June 8, 2020 07:42
Show Gist options
  • Save RP-3/9385121c6da0b42831781d3ea5d7ec26 to your computer and use it in GitHub Desktop.
Save RP-3/9385121c6da0b42831781d3ea5d7ec26 to your computer and use it in GitHub Desktop.
/**
* @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