Number of 1 Bits
You're given a positive integer n. Return how many 1 bits appear in its binary representation, a count also known as the Hamming weight or population count.
Examples
n = 13 returns 3
13 is 1101 in binary, which has three 1 bits.
n = 64 returns 1
64 is a power of two, 1000000 in binary, so it has a single 1 bit.
n = 2147483647 returns 31
The largest 32-bit signed integer is thirty-one 1 bits in a row.
Constraints
- 1 <= n <= 2^31 - 1
Hints
You could test every bit, but is there a way to jump straight from one 1 bit to the next?
Look at what n - 1 does to the binary form of n, and what n & (n - 1) leaves behind.
Count how many times you can set n = n & (n - 1) before n becomes 0. Each step removes exactly one 1 bit.
Drill This: Your Approach First
Approach
n & (n - 1) clears the lowest set bit of n: subtracting 1 flips that bit to 0 and every bit below it to 1, and the AND keeps only the bits above it. Apply it until n reaches 0 and count the rounds. The loop runs once per 1 bit, at most 32 times. Shifting right and testing n & 1 also works, but always takes as many rounds as the highest set bit's position.
Time
O(1)
Space
O(1)
Pitfall
Solutions
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 count