【LeetCode】67. 二进制求和

【LeetCode】67. 二进制求和_第1张图片

解题思路

python 代码

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        ss = []
        aa = list(a)
        aa.reverse()
        bb = list(b)
        bb.reverse()
        carry = 0
        mmm = min(len(a),len(b))
        for i in range(0,mmm):
            s = int(aa[i])+int(bb[i])+carry
            carry = s//2
            s = s%2
            ss.append(str(s))
        if len(a)>mmm:
            for i in range(mmm,len(a)):
                s = int(aa[i])+carry
                carry = s//2
                s = s%2
                ss.append(str(s))
        if len(b)>mmm:
            for i in range(mmm,len(b)):
                s = int(bb[i])+carry
                carry = s//2
                s = s%2
                ss.append(str(s))
        if carry:
            ss.append("1")
        ss.reverse()
        return "".join(ss)

你可能感兴趣的:(数据结构与算法)