leetcode 67. 二进制求和 (又一道自己完全做出来的题目!!!yeah)

虽然时间复杂度很高 算法也是很笨
但是又自己做出来一道题 真开心呀!!
Love this feeling


class Solution(object):

    def addBinary(self, a, b):

        a=[int(char) for char in str(a)]  ##转成整数列表,为了加起来方便
        b=[int(char) for char in str(b)]
        if len(a)>len(b):  ##若长度不等,用0填充
            b=(len(a)-len(b))*[0]+b
        if len(b)>len(a):
            a=(len(b)-len(a))*[0]+a
        c=0
        for i in range(len(a)):
            count=a[-1-i]+b[-1-i]+c  ##各位相加再加进位
            if count==1 or count==0:
                c=0      
            if count>1 and count%2==0:  ##为偶数,则置当前位 为0,进位置一
                c=1
                count=0
            elif count>1 and count%2==1: ##为奇数,则置当前位 为1,进位置一
                c=1
                count=1
            a[-i-1]=count     ##将当前的结果更新a的值,a代表相加结果 
        if c==1:  ##如果C=1 说明有进位,则最前面的字符串加一
            a=[str(i) for i in a]#转成字符串 才能join转成列表
            a="".join(a)
            return "1"+a     
        a=[str(i) for i in a]  ##无进位,则直接转为列表
        a="".join(a)
        return a
            

有一个看起来简单一点的做法 但我没有看懂 因为对Python的函数还不是全部了解
以后再看看吧(这个算法复杂度比我的还高 嘿嘿)

class Solution:
    """
    @param a: a number
    @param b: a number
    @return: the result
    """
    def addBinary(self, a, b):
        # write your code here
        a = list(a)
        b = list(b)
        carry = 0
        res = ""
        while len(a) != 0 or len(b) != 0:
            if len(a) != 0:
                tmp1 = int(a.pop())
            else:
                tmp1 = 0
            if len(b) != 0:
                tmp2 = int(b.pop())
            else:
                tmp2 = 0
            tmp = divmod(tmp1+tmp2+carry, 2)
            carry = tmp[0]
            res = str(tmp[1]) + res
        if carry == 1:
            res = str(carry) + res
        return res

--------------------- 
作者:CherryCheekAir 
来源:CSDN 
原文:https://blog.csdn.net/u010342040/article/details/80333366 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_40929147/article/details/89329564