Created
August 4, 2020 08:55
-
-
Save RP-3/868c70705a8b54b0fc40040d554c1874 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} num | |
* @return {boolean} | |
*/ | |
/* | |
Idea: A power of four is just a non-negative int | |
with one bit set in at an even index. | |
So we need to make sure that the given int is: | |
- non-negative | |
- has just one bit set | |
- that bit is at an even index | |
- If the bit is at an odd index it's a power of 2, | |
but not a power of 4. | |
*/ | |
// O(1) space and time | |
var isPowerOfFour = function(num) { | |
if(num & (num-1)) return false; // more than one bit set | |
if(num <= 0) return false; // negative | |
const mask = 0xAAAAAAAA >> 1; | |
// 0xA = 1010, 0xAA = 10101010 etc | |
// Therefore 0xAA... >> 1 = 010101... | |
return num & (0xAAAAAAAA >> 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment