Number of 1 Bits
Problem
Given a positive integer n, return the number of 1 bits in its binary representation (its Hamming weight).
Example 1
- Input
n = 11- Output
3- Why
- 11 is 1011 in binary.
Example 2
- Input
n = 128- Output
1- Why
- 10000000.
Constraints
- 1 ≤ n ≤ 2³¹ – 1
Explanation
Checking all 32 bits works. A neater trick: n & (n - 1) clears the lowest set bit of n. Repeat until n is 0 and count the steps; the loop runs once per set bit.
Approach 1 · Naive
Check every bit
- Time O(32)
- Space O(1)
Look at the lowest bit, add it to the count, and shift right, 32 times.
- While
n != 0: addn & 1, then shiftnright by one.
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
}
return count;
}
}class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return countApproach 2 · Optimal
Clear the lowest set bit
- Time O(number of set bits)
- Space O(1)
Each n &= n - 1 removes exactly one set bit.
- While
n != 0:n &= n - 1, count++.
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
}class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return countComplexity compared
| Approach | Time | Space |
|---|---|---|
| Naive Check every bit | O(32) | O(1) |
| Optimal Clear the lowest set bit | O(number of set bits) | O(1) |
Key takeaways
n & (n - 1) == 0also tests whethernis a power of two.- In Java use
>>>(unsigned shift) when bits may be negative;>>copies the sign bit forever.
Your notes
Saved in this browser as you type.
Solved it on your own?
Mark it done to track your progress, or star it to come back before an interview.