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
Hamming Weight: Counting Set BitsMethod 1: Check each bit (Brute Force)1011Check all 4 positions โ†’ Count = 3Method 2: Brian Kernighan's AlgorithmStep 1: 1011 & 1010 = 10101010โ†’ Count: 1Step 2: 1010 & 1001 = 10001000โ†’ Count: 2Step 3: 1000 & 0111 = 00000000โ†’ Count: 3Key Insightn & (n-1)clears rightmostset bit
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.
Asked in
Apple 45 Google 38 Microsoft 32 Amazon 28
98.0K Views
High Frequency
~12 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen