Number of 1 Bits - Problem
Given a positive integer n, write a function that returns the number of set bits in its binary representation. This is also known as the Hamming weight.
A set bit is a bit that has a value of 1. For example, the binary representation of 11 is 1011, which has three set bits.
Goal: Count how many '1' bits appear in the binary representation of the given number.
Example: For n = 11 (binary: 1011), the answer is 3 because there are three '1' bits.
Input & Output
example_1.py โ Basic case
$
Input:
n = 11
โบ
Output:
3
๐ก Note:
The binary representation of 11 is 1011, which contains three '1' bits.
example_2.py โ Power of 2
$
Input:
n = 8
โบ
Output:
1
๐ก Note:
The binary representation of 8 is 1000, which contains only one '1' bit.
example_3.py โ All bits set
$
Input:
n = 15
โบ
Output:
4
๐ก Note:
The binary representation of 15 is 1111, which contains four '1' bits.
Constraints
- 1 โค n โค 231 - 1
- The input is guaranteed to be a 32-bit unsigned integer
- You must handle the number as an unsigned integer in languages that support it
Visualization
Tap to expand
Understanding the Visualization
1
Identify the pattern
n & (n-1) always clears the rightmost 1-bit
2
Apply repeatedly
Each operation removes exactly one set bit
3
Count operations
Number of operations equals number of set bits
4
Terminate when n=0
All set bits have been cleared
Key Takeaway
๐ฏ Key Insight: Brian Kernighan's algorithm `n & (n-1)` eliminates exactly one set bit per iteration, making it optimal for sparse bit patterns where most bits are 0.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code