Skip to content

Commit 12fac38

Browse files
committed
added binary solutions
LeetCode
1 parent 8ba4e67 commit 12fac38

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

add_binary.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Learn Python together
2+
3+
"""Given two binary strings a and b,
4+
return their sum as a binary string."""
5+
6+
# Solution
7+
# we can use bin function and change types
8+
def addBinary(a:str, b:str) -> str:
9+
return str(bin(int(a, 2) + int(b, 2)))[2:]
10+
11+
# check
12+
print(addBinary("1010",'1011')) # Output -> 10101
13+
print(addBinary('0','0')) # Output -> 0
14+
print(addBinary('0','1')) # Output -> 1
15+
16+
17+
def addBinary2(a:str, b:str) -> str:
18+
19+
carryover = 0
20+
result = ""
21+
22+
# using for loop and max function to iterate
23+
# through the strings starting from the last index
24+
for i in range(max(len(a), len(b))):
25+
26+
# geting the numbers at the current index of each string, or 0 if beyond the limit
27+
a_num = int(a[::-1][i]) if i < len(a) else 0
28+
b_num = int(b[::-1][i]) if i < len(b) else 0
29+
30+
# sum of numbers and carryover
31+
total = a_num + b_num + carryover
32+
33+
# result would be the rest of total divided by 2 + result that was before
34+
result = str(total % 2) + result
35+
36+
# carryover is 1 if total is greater than 1, otherwise 0
37+
carryover = 1 if total > 1 else 0
38+
39+
# add any remaining carryover to the beginning of result
40+
if carryover == 1:
41+
result = "1" + result
42+
43+
return result
44+
45+
# check
46+
print(addBinary2("1010",'1011')) # Output -> 10101
47+
print(addBinary2('0','0')) # Output -> 0
48+
print(addBinary2('0','1')) # Output -> 1

0 commit comments

Comments
 (0)