12 / 75
Count the number of set bits (1s) in the binary representation of an integer.
Example:
Input:
n = 11 (binary: 1011)Output:
3Common Mistakes:
- Using n % 2 and n /= 2 (less efficient)
- Not handling unsigned integers correctly
- Iterating all 32 bits instead of just set bits
Notes:
Brian Kernighan's algorithm: n & (n-1) removes the rightmost set bit. Time: O(number of 1s), not O(32).
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Count the number of set bits (1s) in the binary representation of an integer.
Example:
Input:
n = 11 (binary: 1011)Output:
3Common Mistakes:
- Using n % 2 and n /= 2 (less efficient)
- Not handling unsigned integers correctly
- Iterating all 32 bits instead of just set bits
Notes:
Brian Kernighan's algorithm: n & (n-1) removes the rightmost set bit. Time: O(number of 1s), not O(32).
12/75
Number of 1 Bits