Power of Two - Problem

Determine whether a given integer is a power of two. A power of two is any integer that can be expressed as 2x where x is a non-negative integer.

For example:

  • 1 = 20 ✅ (power of two)
  • 8 = 23 ✅ (power of two)
  • 6 ❌ (not a power of two)

Your task is to return true if the number is a power of two, and false otherwise. This problem tests your understanding of mathematical properties and bit manipulation techniques.

Input & Output

example_1.py — Python
$ Input: n = 1
Output: true
💡 Note: 1 = 2^0, so it is a power of two
example_2.py — Python
$ Input: n = 16
Output: true
💡 Note: 16 = 2^4, so it is a power of two
example_3.py — Python
$ Input: n = 3
Output: false
💡 Note: 3 cannot be expressed as 2^x for any integer x

Constraints

  • -231 ≤ n ≤ 231 - 1
  • Follow-up: Could you solve it without loops/recursion?

Visualization

Tap to expand
Powers of Two: Binary Patterns2⁰ = 10001₂2¹ = 20010₂2² = 40100₂2³ = 81000₂Pattern: Exactly ONE bit is set!The Magic Formula: n & (n-1) == 0Example: n = 8 8 = 1000₂ 8-1 = 0111₂8 & 7 = 0000₂ = 0 ✓Counter-example: n = 6 6 = 0110₂ 6-1 = 0101₂6 & 5 = 0100₂ ≠ 0 ✗Time Complexity: O(1) | Space Complexity: O(1)
Understanding the Visualization
1
Identify the Pattern
Powers of two in binary: 1₂, 10₂, 100₂, 1000₂...
2
Apply Bit Magic
n & (n-1) removes the rightmost set bit
3
Check Result
If result is 0 and n > 0, then n is a power of two
Key Takeaway
🎯 Key Insight: Powers of two have exactly one bit set in binary, making `n & (n-1) == 0` a perfect O(1) test!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.6K Views
High Frequency
~8 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