[6 kyu] Bit Counting
文章目录
[6 kyu] Bit CountingQuestionSample TestsMy Answer (accepted)Suggested Answer
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")
转载请注明原文地址: https://lol.8miu.com/read-21423.html