トピックリンク:https://leetcode-cn.com/problems/number-of-1-bits/)
件名の説明:
書き込み機能は、入力数のバイナリ表記における桁数を返す符号なし整数であり、「1」(別名ハミング重み)。
例:
例1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
例2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
アイデア:
1つのアイデア:ライブラリ関数
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count("1")
アイデア2:ビット演算
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n:
res += (n & 1)
n >>= 1
return res