题解 | #二进制中1的个数#
二进制中1的个数
https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型
# @return int整型
#该题中二进制有32位,所以模为2**32,补码就是该数与模的差值。如-1表示1的补码,等于2**32-1
class Solution:
def NumberOf1(self , n: int) -> int:
# write code here
if n<0:
return Solution.NumberOf1(self,2**32+n)
s=bin(n)
ans=0
for i in s:
if i == '1':
ans+=1
return ans

途虎成长空间 159人发布