Bit manipulation · Easy
Number of 1 Bits: the idea to remember.
Count the set bits in a 32 bit integer bit pattern.
The core insight
Repeatedly replace n with n AND n minus one; each replacement clears exactly one set bit.
Why it works
Subtracting one flips the lowest one to zero and the lower zeros to ones. AND therefore removes only that one.
The mistake to avoid
Use n != 0, not n > 0, if interpreting signed Java ints as all 32 bits.
Time: O(number of set bits), at most 32Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.