Leetcode刷题笔记python---二进制求和

二进制求和

题目

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0。

示例 1:

输入: a = “11”, b = “1”
输出: “100”
示例 2:

输入: a = “1010”, b = “1011”
输出: “10101”


解答

思路:

  1. 转换成二进制的函数
  2. 转换成10进制的函数
  3. 求解

代码:

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%

猜你喜欢

转载自blog.csdn.net/sinat_29350597/article/details/82989795