-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd Binary.py
66 lines (61 loc) · 1.31 KB
/
Add Binary.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def addBinary(a: str, b: str) -> str:
print(bin(int(a, 2) + int(b, 2))[2:])
ans = ""
i = len(a) - 1
j = len(b) - 1
carry = 0
while i >= 0 and j >= 0:
print("hello")
temp = int(a[i]) + int(b[j]) + carry
if temp == 0:
ans += "0"
carry = 0
elif temp == 1:
ans += "1"
carry = 0
elif temp == 2:
ans += "0"
carry = 1
else:
ans += "1"
carry = 1
i -= 1
j -= 1
while i >= 0:
temp = int(a[i]) + carry
if temp == 0:
ans += "0"
carry = 0
elif temp == 1:
ans += "1"
carry = 0
elif temp == 2:
ans += "0"
carry = 1
else:
ans += "1"
carry = 1
i -= 1
while j >= 0:
temp = int(b[j]) + carry
if temp == 0:
ans += "0"
carry = 0
elif temp == 1:
ans += "1"
carry = 0
elif temp == 2:
ans += "0"
carry = 1
else:
ans += "1"
carry = 1
j -= 1
if carry == 1:
return (ans + str(carry))[::-1]
else:
return ans[::-1]
a = "111"
b = "1"
ans = addBinary(a, b)
print(ans)