Leetcode 67. Add Binary

Description: Given two binary strings a and b, return their sum as a binary string.

Link: 67. Add Binary

Examples:

Example 1:
Input: a = "11", b = "1"
Output: "100"

Example 2:
Input: a = "1010", b = "1011"
Output: "10101"

思路: 二进制加法,先把a, b补齐,长度相同,短的前面补0,这样就不用后面还要判断。进位carry。

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        m, n = len(a), len(b)
        if m < n:
            a = "0"*(n-m)+a
        else:
            b = "0"*(m-n)+b
        a, b = list(a), list(b)
        res, carry = "", 0
        while a and b:
            cur = int(a.pop()) + int(b.pop()) + carry
            if cur >= 2:
                carry = 1
                cur = cur % 2
            else:
                carry = 0
            res = str(cur) + res
        if carry == 1:
            res = "1" + res
        return res

日期: 2021-04-25 是周日啊,阴天,今天晨跑完好累

原文地址:https://www.cnblogs.com/wangyuxia/p/14699239.html