问题描述:
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
示例 :
输入: 11
输出: 3
解释: 整数 11 的二进制表示为00000000000000000000000000001011
示例 2:
输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000
方法1:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
str_b =str(bin(n))
return str_b.count('')
直接可以
return bin(n).count('1')
官方:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
new_n = bin(n)[2:].zfill(31)
new_n = list(new_n)
return new_n.count('')
在这里只是提一下zfill函数
描述
Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
语法
zfill()方法语法:
str.zfill(width)
参数
- width -- 指定字符串的长度。原字符串右对齐,前面填充0。
返回值
返回指定长度的字符串。
实例
以下实例展示了 zfill()函数的使用方法:
#!/usr/bin/python str = "this is string example....wow!!!"; print str.zfill(40);
print str.zfill(50);
以上实例输出结果如下:
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!! 2018-09-16 09:17:03