
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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?
- Python program to count total set bits in all number from 1 to n.
- C# program to count total set bits in a number
- Count set bits using Python List comprehension
- 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.
- Sort an array according to count of set bits in C++
- Python program to reverse bits of a positive integer number?
- Program to count operations to remove consecutive identical bits in Python

Advertisements