给定一个无符号整数,返回该整数二进制表示中"1"的个数
Example 1:
Input: 11 Output: 3 Explanation: Integer 11 has binary representation00000000000000000000000000001011
Example 2:
Input: 128 Output: 1 Explanation: Integer 128 has binary representation 00000000000000000000000010000000
1:整数转二进制的基本方法,判断每一次求余数时余数是否为"1",是的话就累加
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
while n>0:
res = n%2
if res==1:
sum += 1
n = n//2
return sum
2:bin()+count()方法(参考他人代码)
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1')
3:位运算(参考他人代码)
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
while n>0:
sum += n&1
n = n>>1
return sum
4:模拟位运算(参考他人代码)
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
bit = 1
while bit<=n:
if bit&n>0:
sum += 1
bit *= 2
return sum
算法题来自:https://leetcode-cn.com/problems/number-of-1-bits/description/