python输入一个整数,输出该数二进制表示中1的个数

# -*- coding:utf-8 -*-

class Solution:
    def NumberOf1(self, n):
        # write code here
        cnt = 0
        if n<0:
            n = n & 0xffffffff
        while n:
            cnt+=1
            n = (n-1) & n
        return cnt

通过按位与,巧妙的计算出二进制中"1"的个数。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章