[LeetCode] 67. Add Binary_Easy tag: String

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 = ''*(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 '' + ans[::-1]
上一篇:android 屏幕尺寸的理解


下一篇:LIFO栈 ADT接口 数组实现