While looking at some SageMath code I came across the following snippet:
bits = n - sum(n.digits(2))
Since I had no idea what digits
did 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?