Number of 1 Bits
Easy · Bit Manipulation · Explanation and code example
Built-In Function
How it works
We want to find the Hamming Weight of a number, which means counting how many 1 bits are present in its binary representation.
Most programming languages provide:
- a way to convert a number into binary form, or
- a built-in utility to count set bits
Instead of manually checking each bit using bit manipulation, we can rely on these built-in features. This makes the solution short, easy to understand, and less error-prone, especially for beginners.
This approach focuses on clarity and simplicity, not on low-level optimizations.
Steps
- Convert the given number
ninto its binary representation (using a built-in binary conversion or bit-count utility provided by the language). - Count the number of
1bits in that representation. - Return the count.
Complexity
- Time complexity:
O(1) - Space complexity:
O(1)
Things to watch for
Signed vs Unsigned Integer Handling
In some languages, right-shifting a signed negative integer fills with 1s (arithmetic shift) instead of 0s (logical shift). This can cause infinite loops when using while (n != 0) with negative inputs. Use unsigned types or the >>> operator in languages that support it.
Using Division Instead of Bit Shift
While n / 2 and n >> 1 produce the same result for positive integers, division can behave differently for negative numbers and is generally slower. Stick to bitwise operations for clarity and consistency with the problem's intent.
Python code example
class Solution:
def hammingWeight(self, n: int) -> int:
return bin(n).count('1')
C++ code example
class Solution {
public:
int hammingWeight(uint32_t n) {
return __builtin_popcount(n);
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.