LeetCode--191--位1的个数

问题描述:

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 :

输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011

示例 2:

输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000

方法1:

1 class Solution(object):
2     def hammingWeight(self, n):
3         """
4         :type n: int
5         :rtype: int
6         """
7         str_b =str(bin(n))
8         return str_b.count('1')

直接可以

return bin(n).count('1')

官方:

1 class Solution(object):
2     def hammingWeight(self, n):
3         """
4         :type n: int
5         :rtype: int
6         """
7         new_n = bin(n)[2:].zfill(31)
8         new_n = list(new_n)
9         return new_n.count('1')

在这里只是提一下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
原文地址:https://www.cnblogs.com/NPC-assange/p/9655076.html