Number of 1 Bits - Problem

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

A set bit is a bit that has a value of 1 in the binary representation of a number.

Input & Output

Example 1 — Basic Case
$ Input: n = 11
Output: 3
💡 Note: 11 in binary is 1011, which has three 1-bits at positions 0, 1, and 3
Example 2 — Power of Two
$ Input: n = 8
Output: 1
💡 Note: 8 in binary is 1000, which has exactly one 1-bit at position 3
Example 3 — All Bits Set
$ Input: n = 7
Output: 3
💡 Note: 7 in binary is 111, which has three consecutive 1-bits

Constraints

  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Number of 1 Bits Problem OverviewConvert decimal to binary and count the set bitsInput11DecimalBinary Conversion10111011Output3Set bitsCount the green boxes (1-bits): 1 + 0 + 1 + 1 = 3The Hamming weight of 11 is 3
Understanding the Visualization
1
Input
Given integer n = 11
2
Convert to Binary
11 → 1011 in binary
3
Count Set Bits
Count the number of 1s = 3
Key Takeaway
🎯 Key Insight: Use bit manipulation tricks like n & (n-1) to efficiently count only the set bits
Asked in
Apple 25 Microsoft 22 Google 18
125.0K Views
Medium Frequency
~15 min Avg. Time
4.2K 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