二进制中1的个数

题目描述

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

解答

# coding:utf-8

class Solution:
    def NumberOf1(self, n):
        if n < 0:  # 当n是负数,通过& 0xffffffff求得负数的补码
            n = n & 0xffffffff
        count = 0
        while n:
            if n & 1:  # 位与运算
                count += 1
            n = n >> 1  # 右移动一位
        return count

print Solution().NumberOf1(-1)

结束!

原文地址:https://www.cnblogs.com/aaronthon/p/13739241.html