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 = 16true (since 16 = 42)
  • n = 5false (no integer x exists where 4x = 5)
  • n = 1true (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
Powers of Four: Binary Pattern AnalysisDecimal → Binary → Bit Position4⁰ = 1 → 1₂ → Position 0 ✓4¹ = 4 → 100₂ → Position 2 ✓4² = 16 → 10000₂ → Position 4 ✓4³ = 64 → 1000000₂ → Position 6 ✓4⁴ = 256 → 100000000₂ → Position 8 ✓Non-Powers of Four (Counterexamples)8 = 2³ → 1000₂ → Position 3 (odd) ✗32 = 2⁵ → 100000₂ → Position 5 (odd) ✗12 → 1100₂ → Multiple bits ✗Bit Manipulation Formulan > 0 &&(n & (n-1)) == 0 &&(n & 0xAAAAAAAA) == 0Check: positive, single bit, even position
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
67.5K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen