
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements