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
-
Economics & Finance
Python Program to Count set bits in an integer
In this article, we will learn how to count set bits (1's) in the binary representation of an integer. A set bit refers to a bit position that contains the value 1.
Problem statement ? We are given an integer n, we need to count the number of 1's in the binary representation of the number.
For example, the number 15 in binary is 1111, which has 4 set bits.
Method 1: Using Iterative Approach
This approach uses bitwise AND operation to check each bit ?
def count_set_bits(n):
count = 0
while n:
count += n & 1 # Check if last bit is 1
n >>= 1 # Right shift by 1 position
return count
# Test the function
n = 15
print(f"Number: {n}")
print(f"Binary representation: {bin(n)}")
print(f"Set bits count: {count_set_bits(n)}")
Number: 15 Binary representation: 0b1111 Set bits count: 4
Method 2: Using Recursive Approach
This method recursively checks each bit from right to left ?
def count_set_bits_recursive(n):
# Base case
if n == 0:
return 0
else:
# Check last bit and recursively count remaining bits
return (n & 1) + count_set_bits_recursive(n >> 1)
# Test the function
n = 15
print(f"Number: {n}")
print(f"Binary representation: {bin(n)}")
print(f"Set bits count: {count_set_bits_recursive(n)}")
Number: 15 Binary representation: 0b1111 Set bits count: 4
Method 3: Using Built-in bin() Function
Python provides a simple way to count set bits using string methods ?
def count_set_bits_builtin(n):
return bin(n).count('1')
# Test with multiple numbers
numbers = [15, 7, 8, 31]
for num in numbers:
print(f"Number: {num}, Binary: {bin(num)}, Set bits: {count_set_bits_builtin(num)}")
Number: 15, Binary: 0b1111, Set bits: 4 Number: 7, Binary: 0b111, Set bits: 3 Number: 8, Binary: 0b1000, Set bits: 1 Number: 31, Binary: 0b11111, Set bits: 5
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Iterative | O(log n) | O(1) | Understanding bit operations |
| Recursive | O(log n) | O(log n) | Learning recursion |
| Built-in | O(log n) | O(1) | Quick implementation |
Conclusion
We explored three methods to count set bits in an integer. The iterative approach is most efficient, while the built-in method offers simplicity. Choose based on your specific requirements and performance needs.
