Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Input: n = 11
Output: 3
Explanation: The input binary string 1011 has a total of three set bits.
Input: n = 128
Output: 1
Explanation: The input binary string 10000000 has a total of one set bit.
Input: n = 2147483645
Output: 30
Explanation: The input binary string 1111111111111111111111111111101 has a total of thirty set bits.
Follow up: If this function is called many times, how would you optimize it?
Counting the number of 1 bits in an integer can be approached by iterating through each bit and checking whether it is 1. This can be efficiently done by using bit shifts.
The brute force approach can be optimized by using a clever trick with bit manipulation. By repeatedly turning off the rightmost 1-bit, we can directly count the 1-bits without checking each individual bit.
Doing n & (n - 1) removes the rightmost 1-bit from n.
Why?
Each application of this operation removes one set bit. So if we repeat this process and count how many times it happens, the count equals the number of 1-bits.
This allows us to skip all zero bits and only operate on actual 1-bits making it much faster than a brute force bit scan.
Let’s count the 1-bits in: n = 13 → binary: 1101
n is not zero.n = n & (n - 1) to turn off the lowest 1-bit.n becomes zero, return the counter.