Number of 1 Bits
Difficulty: Easy
Given an unsigned 32-bit integer, count how many 1s are in its binary (base-2) form. This count is called the Hamming weight.
For example, 11 in binary is 1011, which has three 1 bits.
Examples
Input: n = 11 (binary: 00000000000000000000000000001011)
Output: 3
The binary form has three 1 bits, at the positions worth 8, 2, and 1.
Input: n = 128 (binary: 00000000000000000000000010000000)
Output: 1
128 is a power of two, so it has exactly one 1 bit.
Input: n = 0
Output: 0
Zero has no 1 bits at all.
Constraints
The input is an unsigned integer represented using 32 bits.
0 <= n <= 2^32 - 1
Approach
The direct way checks all 32 positions: shift the number right by 0 to 31, look at the last bit each time, and count the 1s.
A faster way skips the 0 bits. For any n, n & (n - 1) clears exactly its lowest 1 bit and leaves every other bit as it was. Subtracting 1 flips the trailing 0s to 1s and the lowest 1 to a 0; the AND keeps only the bits that agree.
Repeat this until n is 0 and count the steps. You do one step per 1 bit instead of 32 checks every time.
Solutions
Brute Force - Check Every Bit Position
Shift the number right by 0 to 31 and check whether the last bit is 1. The unsigned shift means the sign never matters.
function hammingWeight(n) {
let count = 0;
for (let i = 0; i < 32; i++) {
if ((n >>> i) & 1) {
count++;
}
}
return count;
}Time: O(1) - always exactly 32 checks · Space: O(1)
Optimal - Clear the Lowest Set Bit Repeatedly
Replace n with n & (n - 1), which clears its lowest 1 bit, until n is 0. The number of steps is the number of 1 bits.
function hammingWeight(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count++;
}
return count;
}Time: O(k), where k is the number of 1 bits in n (at most 32) · Space: O(1)