NeetCode #893LC-342EasyMath & Geometry
← Back to All Problems#893 · #342 · Power of Four(4 的幂)
📌 Problem Statement & Constraints
Given an integer
n, return true if it is a power of four, otherwise false. Constraints: -2^31 <= n <= 2^31 - 1.💡 Core Algorithmic Approaches
- A power of four must first be a power of two, which means it has exactly one set bit:
n & (n - 1) == 0. - Among powers of two, only those with an even exponent are powers of four, i.e. the single set bit must sit at an even index counted from the least significant bit.
- Masking with
0xAAAAAAAA(which has all odd bit positions set) must yield zero. - A loop dividing by four also works but is O(log n) and needs an explicit non-positive check.
💻 Benchmark Python3 Implementation
class Solution:
def isPowerOfFour(self, n: int) -> bool:
if n <= 0:
return False
# exactly one set bit AND that bit is at an even position
return (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1): two bit operations.
💾 Space Complexity
O(1).
⚠️ Interview Pitfalls & Follow-ups
- Accepting any power of two:
8and32are powers of two but not powers of four, so the even-bit mask is essential. - Masking with
0x55555555instead of0xAAAAAAAA: that masks the even positions, which are exactly the valid ones, so the test would be inverted. - Ignoring non-positive input:
n <= 0must return false;0would otherwise satisfy then & (n - 1)test. - Relying on a modulo loop:
while n % 4 == 0is correct but O(log n) and still needs the non-positive guard.