请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return str(bin(n)).count('1')
执行结果:
通过
显示详情
执行用时 :24 ms, 在所有 Python 提交中击败了52.89%的用户
内存消耗 :13 MB, 在所有 Python 提交中击败了100.00%的用户
解法二
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt=0
while n:
if n%2:
cnt+=1
n=n//2
return cnt
执行结果:
通过
显示详情
执行用时:24 ms, 在所有 Python 提交中击败了45.48%的用户
内存消耗:12.6 MB, 在所有 Python 提交中击败了100.00%的用户
解法三
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt=0
while n:
cnt+=n&0x01
n=n>>1
return cnt
执行结果:
通过
显示详情
执行用时:24 ms, 在所有 Python 提交中击败了45.48%的用户
内存消耗:12.9 MB, 在所有 Python 提交中击败了100.00%的用户
解法四
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt=0
while n:
n=n&(n-1)
cnt+=1
return cnt
执行结果:
通过
显示详情
执行用时:16 ms, 在所有 Python 提交中击败了86.44%的用户
内存消耗:12.6 MB, 在所有 Python 提交中击败了100.00%的用户