1. 程式人生 > >LeetCode--191--位1的個數

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