|
| 1 | +# Power of Two |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +Given an integer `n`, return `true` if it is a power of two. Otherwise, return `false`. |
| 6 | + |
| 7 | +An integer `n` is a power of two, if there exists an integer `x` such that `n == 2^x`. |
| 8 | + |
| 9 | +## Examples |
| 10 | + |
| 11 | +**Example 1:** |
| 12 | +``` |
| 13 | +Input: n = 1 |
| 14 | +Output: true |
| 15 | +Explanation: 2^0 = 1 |
| 16 | +``` |
| 17 | + |
| 18 | +## Approach |
| 19 | + |
| 20 | +### Method 1: Bit Manipulation (Recommended) |
| 21 | +1. Use bit manipulation: n & (n-1) == 0 |
| 22 | +2. Powers of two have only one bit set |
| 23 | +3. Most efficient approach |
| 24 | + |
| 25 | +**Time Complexity:** O(1) - Constant time |
| 26 | +**Space Complexity:** O(1) - No extra space |
| 27 | + |
| 28 | +### Method 2: Mathematical |
| 29 | +1. Keep dividing by 2 until n becomes 1 |
| 30 | +2. Check if n becomes 1 |
| 31 | +3. Less efficient than bit manipulation |
| 32 | + |
| 33 | +**Time Complexity:** O(log n) - Logarithmic time |
| 34 | +**Space Complexity:** O(1) - No extra space |
| 35 | + |
| 36 | +## Algorithm |
| 37 | + |
| 38 | +``` |
| 39 | +1. Check if n > 0 |
| 40 | +2. Return n & (n-1) == 0 |
| 41 | +``` |
| 42 | + |
| 43 | +## Key Insights |
| 44 | + |
| 45 | +- **Bit Manipulation**: Powers of two have only one bit set |
| 46 | +- **Local Optimum**: Check bit pattern efficiently |
| 47 | +- **Global Optimum**: Determine if number is power of two |
| 48 | +- **Space Optimization**: Use only necessary space |
| 49 | + |
| 50 | +## Alternative Approaches |
| 51 | + |
| 52 | +1. **Mathematical**: Divide by 2 repeatedly |
| 53 | +2. **Logarithm**: Use logarithm properties |
| 54 | +3. **Brute Force**: Check all powers of two |
| 55 | + |
| 56 | +## Edge Cases |
| 57 | + |
| 58 | +- Zero: Return false |
| 59 | +- One: Return true (2^0) |
| 60 | +- Negative: Return false |
| 61 | +- Large numbers: Handle efficiently |
| 62 | + |
| 63 | +## Applications |
| 64 | + |
| 65 | +- Bit manipulation |
| 66 | +- Mathematical algorithms |
| 67 | +- Algorithm design patterns |
| 68 | +- Interview preparation |
| 69 | +- System design |
| 70 | + |
| 71 | +## Optimization Opportunities |
| 72 | + |
| 73 | +- **Bit Manipulation**: Most efficient approach |
| 74 | +- **Space Optimization**: O(1) space complexity |
| 75 | +- **Constant Time**: O(1) time complexity |
| 76 | +- **No Extra Space**: Use only necessary space |
0 commit comments