[6 kyu] Bit Counting
Question
Sample Tests
My Answer (accepted)
def count_bits(n):
count = 0
str_bits = ""
if n == 0:
return 0
else:
while n//2 != 0:
last = n%2
str_bits += str(last)
n = n//2
str_bits += str(1)
for i in str_bits:
if int(i) == 1:
count += 1
return count
def count_bits(n):
str_num = bin(n)
ans = 0
for i in str_num[2:]:
if int(i) == 1:
ans += 1
return ans
Suggested Answer
def count_bits(n):
return bin(n).count("1")