Leetcode #342: Power of Four
In this guide, we solve Leetcode #342 Power of Four in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an integer n, return true if it is a power of four. Otherwise, return false.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Bit Manipulation, Recursion, Math
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Example
Input: n = 16
Output: true
Python Solution
class Solution:
def isPowerOfFour(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.