Leetcode刷題筆記python---二進位制求和
阿新 • • 發佈:2018-11-10
二進位制求和
題目
給定兩個二進位制字串,返回他們的和(用二進位制表示)。
輸入為非空字串且只包含數字 1 和 0。
示例 1:
輸入: a = “11”, b = “1”
輸出: “100”
示例 2:
輸入: a = “1010”, b = “1011”
輸出: “10101”
解答
思路:
- 轉換成二進位制的函式
- 轉換成10進位制的函式
- 求解
程式碼:
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
def two2nums(x):
n=len(x)
res=0
for i in range(n):
if int(x[i])==1:
res+=pow(2,n-1-i)
return res
def nums2two(x):
res=[]
if x==0:
return '0'
while x>= 1:
n=0
while pow(2,n)<=x:
n+=1
n=n-1
res.append(n)
x=x-pow(2,n)
k=max(res)+1
s=['0']*k
for j in res:
s[k-j-1]='1'
g=''
for i in s:
g+=i
return g
c=two2nums(a)+two2nums(b)
return nums2two(c)
結果:0%%%%%%%%
太差了!!!對二進位制應該找到最有效的處理方法,這樣這種題就很快了。
python自帶二進位制轉換
程式碼:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
c=int(a,2)+int(b,2)
return bin(c)[2:]
結果:70%