《LeetCode笔记19》:二进制求和

题目:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

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

示例 2:

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary/

解法一:

从后往前依次相加,注意不同字符串的长短关系带来的问题。

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        l1 = len(a)
        l2 = len(b)
        if l1>l2:
            l = l2
            l_max = l1
        else:
            l = l1
            l_max = l2
        x = 0
        s = ''
        for i in range(1, l+1):
            y = int(a[-i])+int(b[-i])+x
            s = str(y%2)+s
            x = y//2
        else:
            for i in range(l+1, l_max+1):
                if x == 0:
                    if(l1>l2):
                        s = a[0:l1-i+1]+s
                    else:
                        s = b[0:l2-i+1]+s
                    return s
                if(l1>l2):
                    y = int(a[-i])+x
                else:
                    y = int(b[-i])+x
                s = str(y%2)+s
                x = y//2
        if x == 0:
            return s
        return '1'+s

 

你可能感兴趣的:(LeetCode)