Number of 1 Bits
Easy · Bit manipulation
Jump to codeCount the set bits in an unsigned 32-bit integer.
Examples
Example 1
n = 11
Output: 3
Example 2
n = 128
Output: 1
Constraints
- 0 <= n <= 2^32 - 1; treat the input as an unsigned 32-bit integer.
Need a hint?
Subtracting one changes the lowest set bit and the bits beneath it.
Real bit manipulation interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Maximize the Bitwise AND of K Elements After Spending an Increment BudgetAmazon
- Implement IPv4 iterators and CIDR expansionOpenAI
- Implement firewall matching with CIDR rulesDatabricks
Solution approach
Repeatedly replace n with n & (n−1), increasing a counter each time, until n becomes zero. Each iteration removes exactly the lowest set bit. Use unsigned semantics or a fixed-width mask when the language treats bitwise values as signed.
Complexity
O(number of set bits) time, at most 32 iterations, and O(1) space.
Python reference solution
def hammingWeight(n):
count = 0
while n:
n &= n - 1
count += 1
return count
JavaScript solution
function hammingWeight(n) {
let count = 0;
// Bitwise operators use 32 bits; >>> keeps the value unsigned.
n = n >>> 0;
while (n !== 0) { n = (n & (n - 1)) >>> 0; count++; }
return count;
}
Java solution
import java.util.*;
class Solution {
public int hammingWeight(long n) {
int count = 0;
while (n != 0) { n &= n - 1; count++; }
return count;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int hammingWeight(long long n) {
int count = 0;
while (n != 0) { n &= n - 1; count++; }
return count;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 11 ]
3
[ 128 ]
1
[ 2147483645 ]
30
[ 0 ]
0
[ 1 ]
1
Drafts are saved per language in this browser when storage is available.