Power of Four - Problem

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four if there exists an integer x such that n == 4x.

Input & Output

Example 1 — Power of Four
$ Input: n = 16
Output: true
💡 Note: 16 = 4², so it is a power of four
Example 2 — Not a Power of Four
$ Input: n = 5
Output: false
💡 Note: 5 cannot be expressed as 4^x for any integer x
Example 3 — Edge Case
$ Input: n = 1
Output: true
💡 Note: 1 = 4⁰, so it is a power of four

Constraints

  • -2³¹ ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Power of Four - Optimal Solution INPUT n = 16 (integer input) Binary Representation 1 0 0 0 0 16 = 10000 (binary) Powers of 4 Sequence 4^0 = 1 4^1 = 4 4^2 = 16 4^3 = 64 4^4 = 256 ALGORITHM STEPS 1 Check n > 0 16 > 0 is true 2 Power of 2 Check n & (n-1) == 0 16 & 15 = 10000 & 01111 = 0 3 Power of 4 Check Bit at even position mask = 0x55555555 (n & mask) != 0 4 Verify 16 16 = 4^2 (x=2 exists) Bit Positions (0,2,4...) 4 3 2 1 0 Green = valid power of 4 positions FINAL RESULT true 16 is a power of 4 Verification 4^2 = 16 [OK] Bit Check Results n > 0: [OK] Power of 2: [OK] Even bit pos: [OK] Key Insight: A number is a power of 4 if: (1) it's positive, (2) it's a power of 2 (only one bit set), and (3) that single bit is at an EVEN position (0, 2, 4, 6...). Powers of 4 in binary: 1=1, 4=100, 16=10000, 64=1000000 --> bit at positions 0, 2, 4, 6 respectively TutorialsPoint - Power of Four | Optimal Bit Manipulation Approach | O(1) Time & Space
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
180.0K Views
Medium Frequency
~15 min Avg. Time
2.1K 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