#67 Add Binary
Given two binary strings
a
andb
, return their sum as a binary string.
解题思路:
1. 考虑到 string A B 的长度可能不一样所以先补齐零。
2. 然后将string A和B 同一个index的数字求和之后赋予给新的string,new
3. 用for循环去从后往前看new每一个数位是不是大于2。逢二进一。
4.将new转变为string输出。
class Solution:
def addBinary(self, a: str, b: str) -> str:
# let string a and b have the same number of digits
if len(a) > len(b):
b = '0'*(len(a)-len(b)) + b
elif len(b) > len(a):
a = '0'*(len(b)-len(a)) + a
# create a new list to store the sum of int(a) and int(b)
new = [[] for _ in range(len(a))]
for i in range(len(a)-1, -1, -1):
new[i] = int(a[i]) + int(b[i])
# run through every digits of the list backwards
# add 1 to the