|
| 1 | +# Number of 1 Bits |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). |
| 6 | + |
| 7 | +## Examples |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +``` |
| 11 | +Input: n = 00000000000000000000000000001011 |
| 12 | +Output: 3 |
| 13 | +Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. |
| 14 | +``` |
| 15 | + |
| 16 | +## Approach |
| 17 | + |
| 18 | +### Method 1: Bit Manipulation (Recommended) |
| 19 | +1. Use n & (n-1) to remove rightmost 1 bit |
| 20 | +2. Count iterations until n becomes 0 |
| 21 | +3. Most efficient approach |
| 22 | + |
| 23 | +**Time Complexity:** O(k) - Where k is number of 1 bits |
| 24 | +**Space Complexity:** O(1) - No extra space |
| 25 | + |
| 26 | +### Method 2: Bit Shifting |
| 27 | +1. Check each bit by shifting right |
| 28 | +2. Count 1 bits |
| 29 | +3. Less efficient than bit manipulation |
| 30 | + |
| 31 | +**Time Complexity:** O(32) - Constant time |
| 32 | +**Space Complexity:** O(1) - No extra space |
| 33 | + |
| 34 | +## Algorithm |
| 35 | + |
| 36 | +``` |
| 37 | +1. Initialize count = 0 |
| 38 | +2. While n != 0: |
| 39 | + a. n = n & (n-1) |
| 40 | + b. count++ |
| 41 | +3. Return count |
| 42 | +``` |
| 43 | + |
| 44 | +## Key Insights |
| 45 | + |
| 46 | +- **Bit Manipulation**: n & (n-1) removes rightmost 1 bit |
| 47 | +- **Local Optimum**: Count 1 bits efficiently |
| 48 | +- **Global Optimum**: Total number of 1 bits |
| 49 | +- **Space Optimization**: Use only necessary space |
| 50 | + |
| 51 | +## Alternative Approaches |
| 52 | + |
| 53 | +1. **Bit Shifting**: Check each bit individually |
| 54 | +2. **Built-in Function**: Use Integer.bitCount() |
| 55 | +3. **Lookup Table**: Use precomputed table |
| 56 | + |
| 57 | +## Edge Cases |
| 58 | + |
| 59 | +- Zero: Return 0 |
| 60 | +- All 1s: Return 32 |
| 61 | +- Single 1: Return 1 |
| 62 | +- Large numbers: Handle efficiently |
| 63 | + |
| 64 | +## Applications |
| 65 | + |
| 66 | +- Bit manipulation |
| 67 | +- Hamming weight |
| 68 | +- Algorithm design patterns |
| 69 | +- Interview preparation |
| 70 | +- System design |
| 71 | + |
| 72 | +## Optimization Opportunities |
| 73 | + |
| 74 | +- **Bit Manipulation**: Most efficient approach |
| 75 | +- **Space Optimization**: O(1) space complexity |
| 76 | +- **Linear Time**: O(k) time complexity |
| 77 | +- **No Extra Space**: Use only necessary space |
0 commit comments