Problem Statement

Power of Four

You are given a whole number n. Your job is to say true if n is a power of four, and false if it is not. A power of four is a number you get by multiplying 4 by itself some number of times: 1 (that is 4 to the power 0), 4, 16, 64, 256, and so on. The trick we will use looks at the number in binary. Binary is just the way computers write numbers, using only 0s and 1s. Every power of four has exactly one 1 in its binary form, and that single 1 always lands in an even slot (slot 0, 2, 4, and so on), counting from the right starting at 0. So we check three things: n is positive, n has exactly one 1 bit (which makes it a power of 2), and that one 1 bit sits in an even slot.

easyBit ManipulationMathBit ManipulationTime: O(1) · Space: O(1)

Signals to notice

check if number is a power of 4single bit set AND in even positionbit pattern check

Brute force first

keep dividing by 4 until you either land on 1 or break clean divisibility. That direct path works, but it never reveals the bit pattern that makes the check feel almost immediate.

The key insight

first confirm the number is a power of two, then confirm that its single set bit sits in an even position. The mask 0x55555555 marks exactly those even positions, so the pattern of the bits tells you whether the number truly belongs. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on n = 16

start: n = 16 = binary 10000
check 1 (positive): n > 0 -> 16 > 0 -> true, continue
check 2 (power of two): n & (n-1) = 16 & 15 = 10000 & 01111 = 0 -> true, continue
check 3 (even-position bit): mask 0x55555555 has 1s at even bits; set bit is at position 4 (even)
n & 0x55555555 = 16 (nonzero) -> condition != 0 -> true
all three checks pass -> return true

What must stay true

Powers of 4 are powers of 2 where the single set bit is at an even position (bit 0, 2, 4,..). The mask 0x55555555 has 1s only at even positions, so AND-ing filters for this. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

function isPowerOfFour(n):
    if n <= 0: return false
    if n & (n - 1) != 0: return false   // not a power of two
    return (n & 0x55555555) != 0         // single set bit is at an even position

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not understanding why power of 2 isn't enough — 8 (1000) is a power of 2 but its set bit is at position 3 (odd), so it's not a power of 4. The fix is usually to return to the meaning of each move, not just the steps themselves.

Bit Manipulation Pattern