Number of 1 Bits in Python


Suppose we have an unsigned number n. We have to find the number of 1s in a binary representation of this number. This is also known as Hamming Weight. So if the number is like 000000101101, then the result will be 4.

To solve this, we will use these steps −

  • Take the number and convert it into a binary string
  • set count = 0
  • for each character e in a binary string
    • if the character is ‘1’, then increase count by 1
  • return count

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def hammingWeight(self, n):
      """
      :type n: int
      :rtype: int
      """
      n = str(bin(n))
      print(n)
      one_count = 0
      for i in n:
         if i == "1":
            one_count+=1
      return one_count
num = "000000101101"
ob1 = Solution()
print(ob1.hammingWeight(num))

Input

num = "000000101101"

Output

4

Updated on: 28-Apr-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements