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
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!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code