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 −
Let us see the following implementation to get a better understanding −
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))
num = "000000101101"