binary - Why doesn't my bit-counting function work for negative numbers? (Python) -
binary - Why doesn't my bit-counting function work for negative numbers? (Python) -
i'm trying implement function counts 1's in binary representation of integer. why not work negative integers?
def bit_count(n): bits = 0 while n != 0: bits += (n&1) n = n >> 1 homecoming bits
i've done investigation , found using bin(n) , counting 1's in resulting string work instead, i'd find out why version isn't working.
thank you!
edit: clarify, solves big + integers instantly, runs indefinitely - integer.
follow-up question: task impossible in python, given representation of negative numbers?
resolution: prepare problem, used counter while loop ran maximum of 32 times, i.e. getting 32-bit representation of negative numbers. help.
python binary bitwise-operators
Comments
Post a Comment