- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

- Related Questions & Answers
- Find the Number of 1 Bits in a large Binary Number in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Count number of bits changed after adding 1 to given N in C++
- Python program to count total set bits in all number from 1 to n.
- Prime Number of Set Bits in Binary Representation in Python
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if a number has bits in alternate pattern - Set 1 in C++
- Python program to reverse bits of a positive integer number?
- Check if all bits of a number are set in Python
- Number of integers with odd number of set bits in C++
- Count unset bits of a number in C++
- Program to find higher number with same number of set bits as n in Python?
- Minimum number using set bits of a given number in C++
- Next higher number with same number of set bits in C++
- Counting Bits in Python

Advertisements