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 - Brian Kernighan's Algorithm INPUT n = 11 Binary: 1011 1 bit 3 0 bit 2 1 bit 1 1 bit 0 Set bits (1s) are highlighted in blue color Decimal Value: 8 + 0 + 2 + 1 = 11 (2^3 + 2^1 + 2^0) ALGORITHM STEPS 1 Initialize count = 0, n = 11 2 Loop while n != 0 n = n AND (n-1) Iterations: i=1: 1011 AND 1010 = 1010 i=2: 1010 AND 1001 = 1000 i=3: 1000 AND 0111 = 0000 Loop ends (n = 0) 3 Increment count Each iteration removes one set bit 4 Return count count = 3 FINAL RESULT Output: 3 Hamming Weight = 3 Set Bits Found: 1 1 1 Verification 11 = 1011 (binary) 3 ones found - OK Key Insight: Brian Kernighan's Algorithm uses the property that n AND (n-1) clears the lowest set bit. This gives O(k) time complexity where k = number of set bits, instead of O(log n) for checking each bit. TutorialsPoint - Number of 1 Bits | Brian Kernighan's Algorithm
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