共计 372 个字符,预计需要花费 1 分钟才能阅读完成。
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"
解法:
class Solution:
def addBinary(self, a: 'str', b: 'str') -> 'str':
copy_a=a
copy_b=b
if len(a)<=len(b):
copy_a='0'*(len(copy_b)-len(copy_a))+copy_a
else:
copy_b='0'*(len(copy_a)-len(copy_b))+copy_b
result=''
flag=0
for x in range(len(copy_a)-1,-1,-1):
tmp=int(copy_a[x])+int(copy_b[x])+flag
if tmp>1:
flag=1
else:
flag=0
result=str(tmp%2)+result
if flag==1:
result='1'+result
return result
正文完
请博主喝杯咖啡吧!