Power of Four
Easy
Topics
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
0x55555555 (ones at even positions). Answer: true.Input: n = 16 Output: true
Example 2
Input: n = 5 Output: false
Example 3
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) -> yesApproach
- Reject
n <= 0. - Divide by 4 while divisible.
- 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 -> falseComplexity
- 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 == 1without the loop, or forgetting that 1 is itself4^0and 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 == 1import java.util.*;
class Solution {
public boolean isPowerOfFour(int n) {
if (n <= 0) return false;
while (n % 4 == 0) n /= 4;
return n == 1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isPowerOfFour(int n) {
if (n <= 0) return false;
while (n % 4 == 0) n /= 4;
return n == 1;
}
};/**
* @param {number} n
* @return {boolean}
*/ var isPowerOfFour = function(n) {
if (n <= 0) return false;
while (n % 4 === 0) n /= 4;
return n === 1;
};