67. Add Binary
Easy
4721522Add to ListShare
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a
andb
consist only of'0'
or'1'
characters.- Each string does not contain leading zeros except for the zero itself.
Accepted
802,834
Submissions
1,598,514
class Solution:
def addBinary(self, a: str, b: str) -> str:
i,j,summ,carry=len(a)-1,len(b)-1,"",0
while i>=0 or j>=0 or carry:
d1=int(a[i]) if i>=0 else 0
d2=int(b[j]) if j>=0 else 0
summ+=str((d1+d2+carry)%2)
carry=(d1+d2+carry)//2
i,j=i-1,j-1
#print(summ)
return summ[::-1]
小模拟