输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        if n>=0:
            nbin = bin(n)
            count = nbin.count('1')
            return count
        else:
            num = abs(n)
            nbin = bin(num-1)
            count = 32-nbin.count('1')
            return count

编程技巧