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 input

Input: 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⁹

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int countSetBits(int n) {
// Your code goes here
}
};
Test Case

Input:

N