0

While looking at some SageMath code I came across the following snippet:

bits = n - sum(n.digits(2))

Since I had no idea what digitsdid I went ahead to attempt it with a value of n = 5:

n = 5
print(n.digits(2))
[1, 0, 1]

And if I run the complete line the result is (rather obviously)

n = 5
print(sum(n.digits(2)))
2

How could I achieve this in pure python? Conversion to strings and back are dead slow, so I'd like to avoid those. Is there a fast solution to this?

Bernardo Meurer
  • 2,295
  • 5
  • 31
  • 52

1 Answers1

2

If you are looking to the number of non-zero bits :

bin(5).count("1")
FunkySayu
  • 7,641
  • 10
  • 38
  • 61