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)
- Check the last bit of number, if it is 1 then add it to the result.
- Right shift the number by 1.
- 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