Problem Description
Given a positive integer n, determine the number of set bits (1s) in its binary representation. This count is also known as the Hamming weight of the number.
Key Insights
- The problem is essentially counting the number of 1s in the binary representation of a number.
- A common efficient approach uses bit manipulation: repeatedly clear the lowest set bit until n becomes zero.
- The expression n & (n - 1) clears the lowest set bit of n.
- This method only iterates as many times as there are set bits, making it efficient.
Space and Time Complexity
Time Complexity: O(k), where k is the number of set bits, worst-case O(log n) (or O(1) considering 32-bit integers).
Space Complexity: O(1).
Solution
To solve the problem, we use the bit manipulation trick n & (n - 1) which removes the lowest set bit from n. The algorithm is as follows:
- Initialize a counter to 0.
- While n is not zero, update n by n = n & (n - 1), and increment the counter.
- The counter will hold the number of set bits by the end of the loop. This approach leverages efficient bit-level operations and works well even when the function is called frequently.