Leetcode刷題筆記python---位1的個數
阿新 • • 發佈:2018-11-10
位1的個數
題目
編寫一個函式,輸入是一個無符號整數,返回其二進位制表示式中數字位數為 ‘1’ 的個數(也被稱為漢明重量)。
示例 :
輸入: 11
輸出: 3
解釋: 整數 11 的二進位制表示為 00000000000000000000000000001011
示例 2:
輸入: 128
輸出: 1
解釋: 整數 128 的二進位制表示為 00000000000000000000000010000000
解答
思路:
- 轉為二進位制
- 計數
程式碼:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res=[]
while n>=1:
x=0
while pow(2,x)<=n:
x+=1
x=x-1
n=n-pow(2,x)
res.append(x)
return len(res)
結果:3%
還是二進位制的問題。
二進位制:
bin(x)
程式碼:
class Solution(object):
def hammingWeight(self, n) :
"""
:type n: int
:rtype: int
"""
n_two=bin(n)
return n_two.count('1')
結果:93%