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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: