# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
temp = []
if(n>0):
while(n!=0):
temp.append(n%2)
n = n//2
temp.reverse()
return (temp.count(1))
elif(n==0):
return 0
else:
n = abs(n) #先求正数的二进制
while (n != 0):
temp.append(n % 2)
n = n // 2
#然后再补0 补到长度为32
for i in range(len(temp),32):
temp.append(0)
temp.reverse()
#然后再取反
for i in range(len(temp)):
if(temp[i] == 0):
temp[i] = 1
else:
temp[i] = 0
temp.reverse()
check = 1 #表示进位
#然后再加1 取补码
for i in range(len(temp)):
if((temp[i]+check) == 0):
temp[i] = 0
check = 0
elif((temp[i]+check)==1):
temp[i] = 1
check = 0
elif((temp[i]+check)>1):
temp[i] = 0
check=1
if(check==1):
return (temp.count(1)+check)
else:
return (temp.count(1))