This post is completed by 3 users

  • 1
Add to List
Beginner

357. Count Set bits in a given Number

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

Example:

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

Approach:

  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)

Output:

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