LeetCode算法题解——二进制求和问题

 题目:给你两个二进制字符串,返回它们的和(用二进制表示)。输入为非空字符串且只包含数字1和0。

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

思路,将二进制按位相加并且进位,注意要记录最高位的进位。

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        if len(a)>=len(b):
            b = b.zfill(len(a))
        else:
            a = a.zfill(len(b))
        numA = [int(x) for x in a]
        numB = [int(x) for x in b]
        flag = False #记录最高位的进位
        for i in range(len(a)-1,-1,-1):
            if numA[i]+numB[i] <2:
                numA[i] =numA[i]+numB[i]
            else:
                numA[i] = numA[i]+numB[i]-2
                if i!=0:
                    numA[i-1] += 1
                else:
                    flag = True
        if flag:
            numA.insert(0,1)
        numA = [ str(x) for x in numA]
        numA = "".join(numA)
        return numA

 

你可能感兴趣的:(leetcode,leetcode,算法)