Open In App

Count set bits using Python List comprehension

Improve
Improve
Like Article
Like
Save
Share
Report

Write an efficient program to count number of 1s in binary representation of an integer. Examples:

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 11
Output : 3
Binary representation of 11 is 1101 and has 3 set bits

We have existing solution for this problem please refer Count set bits in an integer link. We will solve this problem in Python using List comprehension. Approach is simple,

  1. Convert given number into it’s binary representation using bin(number) function.
  2. Now separate out all 1’s from binary representation of given number and print length of list of 1’s.

Python3




# Function to count set bits in an integer
# in Python
     
def countSetBits(num):
     
    # convert given number into binary
    # output will be like bin(11)=0b1101
    binary = bin(num)
     
    # now separate out all 1's from binary string
    # we need to skip starting two characters
    # of binary string i.e; 0b
    setBits = [ones for ones in binary[2:] if ones=='1']
         
    print (len(setBits))
     
# Driver program
if __name__ == "__main__":
    num = 11
    countSetBits(num)


Output

3

Time Complexity : O(log n)
Auxiliary Space: O(log n)

Below is one-liner solution. 

Python3




num = 11
print (bin(num).count("1"))


Output

3

Time Complexity: O(logn)

Auxiliary Space : O(1)

Approach#3: using while loop

This approach counts the number of set bits (bits with value 1) in the binary representation of the given integer ‘n’. It uses a while loop to perform bitwise AND operation of n with 1 (to check if the least significant bit is 1), increment the count if the result is 1, and then right shift the bits of n by 1. The loop continues until all bits have been checked. Finally, it returns the count of set bits.

Algorithm

1. Initialize a variable count to 0.
2. Loop while n is greater than 0.
3. Use the bitwise operator AND (&) between n and 1 to check if the least significant bit is set.
4. If it is set, increment the count variable.
5. Right shift n by one bit.
6. Return the count variable.

Python3




def count_set_bits(n):
    count = 0
    while n > 0:
        count += n & 1
        n >>= 1
    return count
n=6
print(count_set_bits(n))


Output

2

Time Complexity: O(log n), where n is input
Space Complexity: O(1)



Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads