Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created August 16, 2025 22:04
Show Gist options
  • Save Ifihan/ea6a47946d495d084356fb7a45d4ef42 to your computer and use it in GitHub Desktop.
Save Ifihan/ea6a47946d495d084356fb7a45d4ef42 to your computer and use it in GitHub Desktop.
Power of Four

Question

Approach

To check if n is a power of four, I first ensure that n is positive. Then, I use the property that a power of four is also a power of two, but with its single 1 bit in an odd position (0-indexed). The bitwise check (n & (n-1)) == 0 ensures it’s a power of two. To verify that the 1 bit is in an odd position, I use a mask: 0x55555555 (binary 01010101...), which only has 1s in odd bit positions. If n & 0x55555555 != 0, then n is a power of four.

Implementation

Complexities

  • Time: O(1)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment