14. Count the Number of Set Bits
Given an integer n, return the number of set bits (1s) in its binary representation.
Can you solve it in O(log n) time complexity?
Example 1:
Input: n = 5
Output: 2
Explanation: The binary representation of 5 is 101, which has 2 set bits.
Example 2:
Input: n = 15
Output: 4
Explanation: The binary representation of 15 is 1111, which has 4 set bits.
Now Your Turn!
Pick the correct output for the given inputInput: n = 32
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 ≤ n ≤ 10⁹