负数思路:
添加链接描述
代码实现:
class Solution:
def NumberOf1(self, n):
# write code here
if n==0:
return 0
if n>0:
s=list(bin(n))
return s.count('1')
if n<0:
t=list(bin(-n))
s=t[2:]
s.reverse()
while len(s)<32:
s.append('0')
begin=s.index('1')+1
for i in range(begin,len(s)):
s[i]=str(1-int(s[i]))
return s.count('1')