leetcode之Number of 1 Bits(191)

题目:

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 :

输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011

示例 2:

输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000

python代码:

class Solution(object):
    def hammingWeight(self, n):
        nums = []
        while n >= 1:
            nums.append(n % 2)
            n = n//2
        return nums.count(1)

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/82534953
今日推荐