Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Bit Manipulation High frequency Solution Available Practice Mode

Number of 1 Bits LeetCode Solution

Tags: #Divide and Conquer #Bit Manipulation

Approach Summary

Brian Kernighan: n &= (n-1) clears the lowest set bit. Count iterations until n = 0.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Bit Manipulation Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Bit Manipulation pattern.

Framework: Bit Manipulation • Interview Prep: Tested at FAANG • Explore all Bit Manipulation problems & invariants →

How to Recognize This Pattern

  • "Hamming weight / popcount"
  • n & (n-1) strips the rightmost 1 bit each iteration

Complexity Analysis

Time Complexity

O(1)

Space Complexity

O(1)

Tags

Divide and Conquer Bit Manipulation

Frequently Asked Questions

What is the optimal time and space complexity for Number of 1 Bits?
The optimal solution for Number of 1 Bits achieves O(1) runtime complexity and requires O(1) auxiliary space. Time complexity for Brian Kernighan's algorithm is O(k) where k is the number of set bits (k <= 32). In the worst case (all bits set), it takes 32 iterations, but on average far fewer. Space complexity is O(1) auxiliary space as only a single integer counter is maintained.
How do I identify that Number of 1 Bits requires the Bit Manipulation pattern?
In technical interviews, look for key problem signals: "Hamming weight / popcount"; n & (n-1) strips the rightmost 1 bit each iteration. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Bit Manipulation strategy.
What critical edge cases must be handled in Number of 1 Bits?
Essential edge cases to verify include: n is 0 (has zero 1 bits, loop terminates immediately); n has only a single bit set (e.g., powers of 2 like 1, 2, 4, 1024; finishes in 1 iteration); n is 0xFFFFFFFF (all 32 bits set, maximum count of 32); High order bit set (n >= 2^31; requires unsigned right shift in Java using >>>). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Number of 1 Bits?
Number of 1 Bits is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Apple, Microsoft, Google.
Buy me a coffee
Daily Practice
0/0