Loop Through Bits
Intuition
The simplest approach is to examine each bit of the number one at a time. We check the least significant bit using AND with 1, count it if it is set, then right-shift the number. We repeat until the number becomes zero. This inspects every bit position that could be set, giving us the total count of 1s.
Algorithm
- Initialize a counter to zero.
- While `n` is not zero, check if the least significant bit is 1 using `n & 1`.
- If it is 1, increment the counter.
- Right-shift `n` by one position.
- Return the counter.
O(32) which is O(1) — we check at most 32 bitsSpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
};class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
}
return count;
}
}class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1
n >>= 1
return countfunc hammingWeight(n int) int {
count := 0
for n != 0 {
count += n & 1
n >>= 1
}
return count
}