每周一道算法题(五十一)

2018-04-22  本文已影响32人  CrazySteven

本周题目难度'Easy',使用语言'Python'

题目:给定两个字符串(由'0'和'1'组成),要求将其按二进制相加后以字符串类型返回。eg:a = "11",b = "1",返回"100"

思路:很简单,一位一位的遍历相加即可,直接看代码:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        //算出a,b的长度
        len_a = len(a) - 1
        len_b = len(b) - 1
        //是否进位
        temp = 0
        //容器
        result = []
        //遍历相加
        while (len_a >= 0 or len_b >= 0 or temp):
            if len_a >= 0 or len_b >= 0:
                temp_a = (int(a[len_a]) if(len_a >= 0) else 0)
                temp_b = (int(b[len_b]) if(len_b >= 0) else 0)
                num = temp_a + temp_b + temp
                if (num >= 2):
                    temp = 1
                    result.insert(0,(str(num - 2)))
                else:
                    temp = 0
                    result.insert(0,(str(num)))
            else:
                temp = 0
                result.insert(0,'1')
            len_a -= 1
            len_b -= 1 
        //转换成字符串
        return "".join(result)

效率较低,周末上了两天课,等抽时间再优化吧。


今天优化了一下,嗯,要体现出我大Python的强大,就一行代码解决问题,说下思路,将两个字符串分别转成十进制的数,然后相加,将结果转成二进制,删掉二进制的标识即可,下面是代码:

class Solution:  
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return bin(int(a, 2) + int(b, 2))[2:]

无论是代码量还是效率对于Python都是非常不错的。。。

版权声明:本文为 Crazy Steven 原创出品,欢迎转载,转载时请注明出处!

上一篇 下一篇

猜你喜欢

热点阅读