count number of ones in a given integer

Question:

How do you count the number of ones in a given integer’s binary representation.

Say you are given a number 20, which is 10100 in binary, so number of ones is 2.

Asked By: Neil

||

Answers:

If the input number is ‘number’

number =20
len(bin(number)[2:].replace('0',''))

Another solution is

from collections import Counter

Counter(list(bin(number))[2:])['1']
Answered By: Neil

Use the awesome collections module.

>>> from collections import Counter
>>> binary = bin(20)[2:]
>>> Counter(binary)
Counter({'0': 3, '1': 2})

Or you can use the built-in function count():

>>> binary = bin(20)[2:]
>>> binary.count('1')
2

Or even:

>>> sum(1 for i in bin(20)[2:] if i == '1')
2

But that last solution is slower than using count()

Answered By: TerryA
>>> num = 20
>>> bin(num)[2:].count('1')
2
Answered By: Yarkee

The str.count method and bin function make short work of this little challenge:

>>> def ones(x):
        "Count the number of ones in an integer's binary representation"
        return bin(x).count('1')

>>> ones(20)
2
Answered By: Raymond Hettinger

What you’re looking for is called the Hamming weight, and there are a lot of algorithms to do it. Here’s another straightforward one:

def ones(n):
    w = 0
    while (n):
        w += 1
        n &= n - 1
    return w
Answered By: Cairnarvon

The usual way to make this blinding fast is to use lookup tables:

table = [bin(i)[2:].count('1') for i in range(256)]

def pop_count(n):
   cnt = 0
   while n > 0:
     cnt += table[n & 255]
     n >>= 8
   return cnt

In Python, any solution using bin and list.count will be faster, but this is nice if you want to write it in assembler.

Answered By: Torsten Marek

I am a new coder and I found this one logic simple. Might be easier for newbies to understand.

def onesInDecimal(n):
  count = 0
  while(n!=0):
    if (n%2!=0):
        count = count+1
        n = n-1
        n = n/2
    else:
        n = n/2
  return count
Answered By: Vivek Karn

You can do this using bit shifting >> and bitwise and & to inspect the least significant bit, like this:

def count_ones(x):
    result = 0
    while x > 0:
        result += x & 1
        x = x >> 1
    return result

This works by shifting the bits right until the value becomes zero, counting the number of times the least significant bit is 1 along the way.

Answered By: Brian Pursley

The int type has a new method int.bit_count() since python 3.10a, returning the number of ones in the binary expansion of a given integer, also known as the population count as follows:

n = 20
bin(n)
'0b10100'

n.bit_count() returns 2 as it has 2 ones in the binary representation.

Answered By: Hamza

For a special case when you need to check quickly whether the binary form of the integer x has only a single 1 (and thus is a power of 2), you can use this check:

if x == -(x | (-x)):
    ...

The expression -(x | (-x)) is the number that you get if you replace all 1s except the last one (the least significant bit) in the binary representation of x with 0.

Example:

12 = 1100 in binary

-12 = …110100 in binary (with an infinite number of leading 1s)

12 | (-12) = …111100 in binary (with an infinite number of leading 1s)

-(12 | (-12)) = 100 in binary

Answered By: Andrey Shutovich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.