Number of 1 Bits
Easy· bit counting
Problem
Given a positive integer, return how many 1s appear in its binary representation. This count is also called the Hamming weight.
Examples
Input: n = 11
Output: 3
11 is 1011 in binary.
Input: n = 128
Output: 1
128 is 10000000 in binary.
Constraints
- • 1 <= n <= 2^31 - 1
Hints & approach
Hint 1
You can check the lowest bit with n & 1 and then shift right.
Hint 2
What does n & (n - 1) do to the binary form of n?
Hint 3
It clears the lowest set bit — count how many times you can do that.
Approachtry the hints first
The expression n & (n - 1) removes the lowest set bit of n, because subtracting 1 flips that bit and every zero below it. Repeat until n becomes 0, counting iterations. This runs once per set bit rather than once per bit position.
Time O(number of set bits) · Space O(1)