I am trying to count the number of bits in the given number using python:
def countBit(self, n: int) -> int:
l=[int(d) for d in str(n)]
return(sum(l))
The input given to this function is 00000000000000000000000000001011 and the output expected is 3 but I am getting 2 as the output.
Can you suggest me a way to proceed ?
You're adding the digits in the decimal representation of the number, not the binary representation.
From your expected output, I guess you actually want to only count the 1
bits, not the 0
bits.
Use the bin()
function to convert the number to a binary string.
def countBit(n: int) -> int:
return sum(b == '1' for b in bin(n))