Skip to content

Commit d63c6a1

Browse files
authored
feat: Add Binary addition algorithm in Python
This program adds two binary numbers given as strings and returns their sum as a binary string. Based on LeetCode Problem 67 — Add Binary.
1 parent a71618f commit d63c6a1

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

bit_manipulation/add_Binary.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
def add_Binary(a: str, b: str) -> str:
2+
i, j = len(a) - 1, len(b) - 1 # start from the end of both strings
3+
carry = 0
4+
result = []
5+
6+
while i >= 0 or j >= 0 or carry:
7+
total = carry
8+
9+
if i >= 0:
10+
total += int(a[i]) # convert char to int
11+
i -= 1
12+
if j >= 0:
13+
total += int(b[j])
14+
j -= 1
15+
16+
result.append(str(total % 2)) # current bit
17+
carry = total // 2 # update carry
18+
19+
return ''.join(reversed(result)) # reverse the result to get correct order
20+
21+
22+
# Example usage
23+
if __name__ == "__main__":
24+
a = "1010"
25+
b = "1011"
26+
print("Input: a =", a, ", b =", b)
27+
print("Output:", add_Binary(a, b))

0 commit comments

Comments
 (0)