Number of 1 Bits (LeetCode 191): Solution and Explanation
Given a non-negative integer, count how many of the bits in its binary representation are set to 1. This count is known as the Hamming weight or population count of the number.
Watch it run step by step
Try your own input and write the code →Intuition
The string approach converts the number to binary with something like bin(n) and counts the '1' characters. It is a fine one-liner in Python, but it allocates a string and skips the bit manipulation that the problem is meant to practice.
Working directly on bits, the simplest idea is to look at the lowest bit, which n & 1 gives you as 0 or 1, add it to a counter, and then shift the number right by one so the next bit moves into the lowest position. Repeat until the number becomes zero. Each shift discards the bit you just counted, so every bit is examined exactly once.
Stopping when n reaches zero, rather than always looping 32 times, is a small but real improvement: once all remaining bits are zero there is nothing left to count. For small numbers that means only a few iterations, and for any 32-bit input it is at most 32.
There is an even tighter trick worth knowing. The expression n & (n - 1) clears the lowest set bit of n, so a loop built on it runs once per 1 bit instead of once per bit position. For sparse numbers like 128, that is a single iteration. The reference solution uses the shift loop, which is easier to explain, but the faster version comes up often as a follow-up.
Approach: Check the lowest bit and shift right
- Start with
count = 0. - Loop while
nis not zero. - Add
n & 1tocount, which is 1 exactly when the lowest bit is set. - Shift
nright by one withn >>= 1, dropping the bit that was just counted. - When
nreaches zero, every set bit has been counted, so returncount.
Step-by-step example
n = 11 (binary 1011)
- The lowest bit of 1011 is 1, so
countbecomes 1 andnshifts to 101, which is 5. - The lowest bit of 101 is 1, so
countbecomes 2 andnshifts to 10, which is 2. - The lowest bit of 10 is 0, so
countstays 2 andnshifts to 1. - The lowest bit of 1 is 1, so
countbecomes 3 andnshifts to 0. The loop ends and the function returns 3.
Code: Python, Java, C++
1class Solution:
2 def hammingWeight(self, n: int) -> int:
3 count = 0
4 while n:
5 count += n & 1
6 n >>= 1
7 return count1public class Solution {
2 public int hammingWeight(long n) {
3 int count = 0;
4 while (n != 0) {
5 count += (int)(n & 1L);
6 n >>>= 1;
7 }
8 return count;
9 }
10}1class Solution {
2public:
3 int hammingWeight(uint32_t n) {
4 int count = 0;
5 while (n) {
6 count += n & 1;
7 n >>= 1;
8 }
9 return count;
10 }
11};Time and space complexity
O(log n)
The loop runs once per bit up to the highest set bit, which is about log₂ n iterations and never more than 32 for a 32-bit input, so it is constant time in practice.
O(1)
Only the counter and the shrinking input are stored, so memory use does not depend on the value of n.
Other approaches
Clear the lowest set bit (time O(k), where k is the number of set bits, space O(1))
Repeat n &= n - 1 and count the iterations until n is zero. Each step removes exactly one 1 bit, so the loop runs once per set bit, which is faster for numbers with few ones.
Built-in population count (time O(1), space O(1))
Python's bin(n).count('1') or int.bit_count(), Java's Integer.bitCount and C++'s __builtin_popcount all compute this directly, often with a single hardware instruction.
Common mistakes
- Using an arithmetic right shift on a negative number in Java. The sign bit is copied in, so
nnever reaches zero; use the unsigned shift>>>. - Checking
n % 2and dividing by 2 on negative numbers in languages with signed integers, which can give -1 remainders. - Looping a fixed 32 times while also stopping at zero, which is redundant. Choose one termination rule and keep it consistent.
- Confusing
n & 1withn | 1. The OR always produces an odd number and does not test anything.
Frequently asked questions
What is the Hamming weight of a number?
It is the number of 1 bits in its binary representation. The name comes from the Hamming distance, since the weight of a number equals its distance from zero.
How does n & (n - 1) work?
Subtracting 1 flips the lowest set bit to 0 and every bit below it to 1. AND-ing with the original then clears exactly that lowest set bit and leaves everything above unchanged.
What is the time complexity of Number of 1 Bits?
The shift loop runs once per bit up to the highest set bit, so at most 32 times for 32-bit inputs. The n & (n - 1) version runs once per set bit, which is never more.
How would you optimize it if the function is called many times?
Precompute the bit counts of all 256 byte values, then sum the table entries for each of the four bytes of the input. Hardware popcount instructions are faster still when the language exposes them.