Power of Four

Easybit-manipulationmath
Category: Fundamentals

Approach

Power of Four

Approach

Use bit manipulation to check power of 4 properties.

Algorithm

  1. Check n > 0
  2. Check only one bit set: (n & (n-1)) == 0
  3. Check bit at even position: (n & 0x55555555) != 0

Complexity

  • Time: O(1) - bitwise operations
  • Space: O(1) - constant space

Key Insights

  • Powers of 4: 1, 4, 16, 64, ... (binary: 1, 100, 10000, ...)
  • Must be power of 2 with bit at even position
  • 0x55555555 = 0101...0101 masks even bit positions

Solution

java
1class Solution {
2    public boolean isPowerOfFour(int n) {
3        if (n <= 0) return false;
4        
5        // Check if power of 2 and bit at even position
6        return (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
7    }
8}
Loading visualizer...