-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddBinary
More file actions
33 lines (24 loc) · 711 Bytes
/
addBinary
File metadata and controls
33 lines (24 loc) · 711 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution(object):
def addBinary(self, a, b):
i = len(a) - 1
j = len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += int(a[i])
i -= 1
if j >= 0:
total += int(b[j])
j -= 1
result.append(str(total % 2))
carry = total // 2
result.reverse()
return ''.join(result)
if __name__ == "__main__":
a = input("Enter first binary number: ")
b = input("Enter second binary number: ")
sol = Solution()
result = sol.addBinary(a, b)
print("Binary Sum:", result)