How to Count Number of 1 in Binary Numbers in Python


In this example, we will learn how to count the number of 1 in a given binary number with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Input a number: "))
count = 0
while n:
    n = n & (n - 1)
    count += 1
print('The number of 1s is:', count)

Output:

Input a number: 8
The number of 1s is: 1

Input a number: 9
The number of 1s is: 2

Input a number: 35
The number of 1s is: 3
Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Cory
6 months ago

Perhaps and easier example using inbuilt python functions.

>>> bin(35)
‘0b100011’

>>> bin(35).count(‘1’)
3

>>> bin(35)[2:].count(‘0’)
3