Description
写一个函数,其以无符号整数为输入,而输出对应二进制数所具有的“1”的位数(也被称为汉明权重)
Example
样例 1
输入:n = 11
输出:3
解析:11(10) = 1011(2), 返回 3
样例 2
输入:n = 7
输出:3
解析:7(10) = 111(2), 返回 3
非常简单的binary to decimal 后面算有多少个1就好了
代码:
class Solution:
"""
@param n: an unsigned integer
@return: the number of ’1' bits
"""
def hamming_weight(self, n: int) -> int:
s=""
count=0
while (n >0):
if n%2==1:
n=n//2
s="1"+s
else:
n=n/2
s="0"+s
for i in s:
if i=="1":
count+=1
return count