Count Set bits in a given Number

Objective: Given a Number, find all the set bits in that number.


Number: 23
Set bits: 4 (10111)
Number: 15 
Set bits: 4 (1111)
Number: 21
Set bits: 3 (10101)


  1. Check the last bit of number, if it is 1 then add it to the result.
  2. Right shift the number by 1.
  3. Repeat the first two steps till number is greater than 0.

Time Complexity: O(Logn)



Number of set bits in integer 23 is :4
Number of set bits in integer 16 is :1
Number of set bits in integer 15 is :4

Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

%d bloggers like this: