Reputation: 5234
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
When I run my code below it appears that only two 1's are recognized ... why is that?
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
for i in str(n):
sum += int(i)
return sum
I think I'm misunderstanding some concepts here. Would appreciate some guidance.
Upvotes: 0
Views: 1614
Reputation: 31182
change str(n)
into bin(n)[2:]
. This way you will get binary representation string of n
with omitted "0b" prefix.
BTW, you don't need to count manually in a loop. Python string has .count()
:
return bin(n).count("1")
Upvotes: 0
Reputation: 7280
Python 3.10
introduces int.bit_count() but if you have to implement the algorithm yourself then you can try something like this:
test.py:
def count(n):
bits = 0
while n:
bits += 1
n &= n - 1
return bits
def main():
n = 0b110001010000000000111
c = count(n)
print(f"Bit length: {n.bit_length()}, bits: {c}")
if __name__ == "__main__":
main()
Test:
$ python test.py
Bit length: 21, bits: 7
The time complexity of this algorithm is O(k)
where k
is the number of bits set to 1.
Upvotes: 3