代码改变世界

[LeetCode] 67. Add Binary_Easy tag: String

2018-08-13 04:05  Johnson_强生仔仔  阅读(197)  评论(0编辑  收藏  举报

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

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

Example 2:

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


这个题我们就把a,b补全, 使得他们length相等, 这样, 只需要判断最后一个edge case, 看看是不是需要多加一位.

class Solution:
    def addBinary(self, a, b):
        if len(b) < len(a):
            a, b = b, a
        m, n, ans, pre = len(a), len(b), "", 0
        a = '0'*(n-m) + a
        for i in range(n)[::-1]: # note 从n-1往前走
            pre, rem = divmod(int(a[i]) + int(b[i] + pre, 2))
            ans += str(rem)
        return ans[::-1] if not pre else '1' + ans[::-1]