Number of 1 Bits
Number of 1 Bits
Section titled “Number of 1 Bits”
Easy
Day 3 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given a positive integer n, write a function that returns the number of set bits it has (also known as Hamming weight).
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
n = 11 - Output:
3 - Explanation: 11 in binary is 1011 (3 set bits)
Constraints:
1 <= n <= 2^31 - 1
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”n & (n - 1) clears the lowest set bit.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Brian Kernighan’s Bit Counting Algorithm
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD A["Input Integer / Bits"] --> B["Apply Bitwise Operation (AND / XOR / Shift)"] B --> C{"Check Bit Condition"} C -- "Condition Met" --> D["Update Bit Count / Result"] C -- "Continue" --> E["Shift Bits (>>> 1 or & n-1)"] E --> B D --> F["Return Final Result"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function hammingWeight(n) { let count = 0; while (n > 0) { count += (n & 1); n >>>= 1; } return count;}- Time Complexity:
O(32) - Space Complexity:
O(1) - Explanation: Shift bits right 32 times.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function hammingWeight(n) { let count = 0; while (n !== 0) { n &= (n - 1); count++; } return count;}- Time Complexity:
O(set bits) - Space Complexity:
O(1) - Explanation: Clears lowest set bit in each iteration.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”n & (n - 1) removes the least significant 1-bit in O(k) operations.
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Use n & (n - 1) to clear bits one by one.