

- 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
Python Program to Count set bits in an integer
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an integer n, we need to count the number of 1’s in the binary representation of the number
Now let’s observe the solution in the implementation below −
#naive approach
Example
# count the bits def count(n): count = 0 while (n): count += n & 1 n >>= 1 return count # main n = 15 print("The number of bits :",count(n))
Output
The number of bits : 4
#recursive approach
Example
# recursive way def count( n): # base case if (n == 0): return 0 else: # whether last bit is set or not return (n & 1) + count(n >> 1) # main n = 15 print("The number of bits :",count(n))
Output
The number of bits : 4
Conclusion
In this article, we have learned about how we can make a Python Program to Count set bits in an integer.
- Related Questions & Answers
- Java Program to Count set bits in an integer
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- C/C++ Program to the Count set bits in an integer?
- Count set bits in an integer in C++
- Python Count set bits in a range?
- Count set bits using Python List comprehension
- C# program to count total set bits in a number
- Python program to count total set bits in all number from 1 to n.
- Sort an array according to count of set bits in C++
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- Python program to count unset bits in a range.
- Python program to reverse bits of a positive integer number?
- Program to count operations to remove consecutive identical bits in Python
Advertisements