Number of 1 Bits
Count the 1 bits of a positive integer by clearing its lowest 1 bit until nothing is left.
The problem
You get a positive integer n. Return how many 1 bits its binary form has, a count also known as its Hamming weight.
Input n = 13
Output 3
13 is 1101 in binary.
Input n = 96
Output 2
96 is 1100000 in binary.
How to spot the pattern
- The question is about the binary form of a number.
- You only need to visit the bits that are set, not all 32 of them.
The idea
Subtracting 1 from n turns its lowest 1 bit into a 0 and every 0 below it into a 1, and leaves the higher bits alone. So n & (n - 1) is n with exactly its lowest 1 bit cleared. Repeat until n becomes 0 and count the rounds: the loop runs once per 1 bit.
Brute force: Check all 32 bit positions with (n >> i) & 1, which always takes 32 steps however few bits are set.
Step by step
- 1Start with
count = 0. - 2While
nis not 0, setn = n & (n - 1)and add 1 tocount. - 3Return
count.
Code
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1 # n - 1 flips the lowest 1 bit and the 0s after it, so this clears that bit
count += 1
return countComplexity
Time
O(k)
Space
O(1)
k is the number of 1 bits, at most 31 for a positive 32-bit int, since each round clears one of them.
Watch out for
- Shifting a negative number right with
>>in Java or C++: the sign bit gets copied in, so a shift loop never reaches 0 (Java has>>>for this). - Mixing up
n & (n - 1), which clears the lowest 1 bit, withn & -n, which keeps only the lowest 1 bit.
Follow-up questions
Is there a built-in for this?
Yes: Integer.bitCount in Java, __builtin_popcount in GCC, and n.bit_count() in Python 3.10 and later. Interviewers usually want to see the loop first.
How do you check whether n is a power of two?
A power of two has exactly one 1 bit, so it is a power of two when n > 0 and n & (n - 1) == 0.
In Hinglish
`n & (n - 1)` sabse neeche wala 1 bit mita deta hai. Jitni baar yeh karke n zero hota hai, utne hi 1 bits the.