题目描述:
# Write a function that takes an integer as input,
# and returns the number of bits that are equal to one in the binary
# representation of that number. You can guarantee that input is non-negative.
#
# Example: The binary representation of 1234 is 10011010010,
# so the function should return 5 in this case
我的解答:
def countBits(a):
b = bin(abs(a)).replace('0b', "") # python 自带了方法 bin 函数,比如 bin(12345) 回返回字符串 '0b11000000111001', 这个时候在把0b去掉即可
return b.count("1")
网上解法:
def countBits(a):
return bin(a).count("1")