编写一个函数,该函数采用无符号整数并返回其具有的``1''位数(也称为汉明权重Hamming weight)。
Input: 00000000000000000000000000001011
Output: 3(里面有3个1)
Method 1
先考虑用count的方法查里面有几个1,直接count不行,需要bin转换一下
class Solution:
def hammingWeight(self, n: int) -> int:
res=str(bin(n)).replace('0b','').count('1')
return res
Method 2
按位做与运算,都为1则+1
class Solution:
def hammingWeight(self, n: int) -> int:
res=0
while n:
if n&1: #和190题一样都为1则True, if可以用res+=n&1代替
res+=1
n>>=1
return res
第一个方法显示的20ms第二个24ms第二个好理解一些,但是第一个快一丢丢