Skip to content

Commit b14d96e

Browse files
Added Day-19 Solution
1 parent c37f01c commit b14d96e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Day-19_Add_Binary.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given two binary strings, return their sum (also a binary string).
3+
4+
The input strings are both non-empty and contains only characters 1 or 0.
5+
6+
Example 1:
7+
8+
Input: a = "11", b = "1"
9+
Output: "100"
10+
Example 2:
11+
12+
Input: a = "1010", b = "1011"
13+
Output: "10101"
14+
15+
16+
Constraints:
17+
18+
Each string consists only of '0' or '1' characters.
19+
1 <= a.length, b.length <= 10^4
20+
Each string is either "0" or doesn't contain any leading zero.
21+
22+
'''
23+
24+
class Solution:
25+
def addBinary(self, a, b):
26+
i, j, summ, carry = len(a) - 1, len(b) - 1, "", 0
27+
while i >= 0 or j >= 0 or carry:
28+
d1 = int(a[i]) if i >= 0 else 0
29+
d2 = int(b[j]) if j >= 0 else 0
30+
summ += str((d1 + d2 + carry) % 2)
31+
carry = (d1 + d2 + carry) // 2
32+
i, j = i-1, j-1
33+
return summ[::-1]

0 commit comments

Comments
 (0)