Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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.
Advertisements
