Power of Four

Easy

Topics
MathBit Manipulation

Given an integer n, return true if it is a power of four (i.e., n == 4^x for some non-negative integer x).

Example 1

76543210n = 1600010000mask01010101
A power of four is a power of two whose single set bit sits at an even position. So two checks: one set bit, and that bit survives the mask 0x55555555 (ones at even positions). Answer: true.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 16
Output: true

Example 2

76543210n = 500000101mask01010101
Input:  n = 5
Output: false

Example 3

76543210n = 100000001mask01010101
Input:  n = 1
Output: true

Constraints

  • -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Divide by 4 while it divides evenly; a power of four reduces to exactly 1. The guard for non-positive input comes first, because 0 % 4 == 0 would otherwise loop forever or fall through wrongly.

Worth knowing the bit-level characterisation, because it is the expected answer if the interviewer asks for O(1). A power of four is a power of two whose single set bit sits at an even position. So: n > 0, and n & (n-1) == 0 (exactly one bit set), and that bit falls in the even positions — testable with a mask of alternating bits, 0x55555555.

4   = 0100   one bit, position 2 (even)   -> yes
8   = 1000   one bit, position 3 (odd)    -> no, power of two only
16  = 10000  one bit, position 4 (even)   -> yes

Approach

  1. Reject n <= 0.
  2. Divide by 4 while divisible.
  3. Return whether the result is 1.

Dry Run

n = 16   16 -> 4 -> 1, loop ends, 1 == 1  -> true
n = 8    8 -> 2, 2 % 4 != 0, loop ends, 2 != 1  -> false
n = 1    1 % 4 != 0 immediately, 1 == 1  -> true
n = 0    rejected by the guard  -> false
n = -4   rejected by the guard  -> false

Complexity

  • Time — O(log n) base 4, so at most 16 iterations for a 32-bit input. The bit-mask form is O(1).
  • Space — O(1).

Common Pitfalls

  • Dropping the positivity guard. Zero divides by 4 forever in some formulations, and negatives are never powers of four.
  • Testing only n & (n-1) == 0, which accepts every power of two — 8 would pass.
  • Using log(n) / log(4) and checking for an integer. Floating point makes large powers land just off the mark.
  • Returning n == 1 without the loop, or forgetting that 1 is itself 4^0 and so a valid answer.

Full Solution — all languages

class Solution:
    def isPowerOfFour(self, n):
        if n <= 0:
            return False
        while n % 4 == 0:
            n //= 4
        return n == 1
Asked at Two Sigma
SensAI
Beta
Tap the mic to stop voice mode