Power of Four - Problem
Given an integer n, determine whether it represents a power of four. Return true if n is a power of four, otherwise return false.
A number is a power of four if there exists an integer x such that n = 4x. In other words, n must be one of the values: 1, 4, 16, 64, 256, 1024, ...
Examples:
n = 16→true(since 16 = 42)n = 5→false(no integer x exists where 4x = 5)n = 1→true(since 1 = 40)
This problem tests your understanding of mathematical properties, bit manipulation, and optimization techniques.
Input & Output
example_1.py — Basic Power of Four
$
Input:
n = 16
›
Output:
true
💡 Note:
16 = 4² = 4^2, so 16 is a power of four with x = 2
example_2.py — Not Power of Four
$
Input:
n = 5
›
Output:
false
💡 Note:
There is no integer x such that 4^x = 5. The closest powers of 4 are 4¹ = 4 and 4² = 16
example_3.py — Edge Case
$
Input:
n = 1
›
Output:
true
💡 Note:
1 = 4⁰ = 4^0, so 1 is a power of four with x = 0
Constraints
- -231 ≤ n ≤ 231 - 1
- Follow-up: Could you solve it without loops/recursion?
Visualization
Tap to expand
Understanding the Visualization
1
Identify Powers of 4
1, 4, 16, 64, 256, 1024... follow 4^x pattern
2
Binary Representation
Each has exactly one bit set: 1₂, 100₂, 10000₂, 1000000₂...
3
Bit Position Pattern
The single bit is always at even positions (0, 2, 4, 6...)
4
Apply Bit Magic
Use (n & (n-1)) == 0 and position checking for O(1) solution
Key Takeaway
🎯 Key Insight: Powers of four are the subset of powers of two where the single bit appears at even positions (0, 2, 4, 6...), enabling O(1) verification through bit manipulation.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code