This is a Python program to count set bits in a number.
The program finds the number of ones in the binary representation of a number.
1. Create a function count_set_bits that takes a number n as argument.
2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0.
3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n.
4. Thus the number of operations required to make n zero is the number of set bits in n.
Here is the source code of a Python program count set bits in a number. The program output is shown below.
def count_set_bits(n): count = 0 while n: n &= n - 1 count += 1 return count n = int(input('Enter n: ')) print('Number of set bits:', count_set_bits(n))
1. The user is asked to input n.
2. The number of set bits is found by calling count_set_bits on n.
Case 1: Enter n: 9 Number of set bits: 2 Case 2: Enter n: 31 Number of set bits: 5 Case 3: Enter n: 1 Number of set bits: 1
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Apply for Python Internship
- Practice Programming MCQs
- Check Information Technology Books
- Apply for Programming Internship
- Check Python Books