- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryAdd.py
More file actions
Latest commit
39 lines (32 loc) · 823 Bytes
/
Copy pathBinaryAdd.py
File metadata and controls
39 lines (32 loc) · 823 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
34
35
36
37
38
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
defadd_binary(str1,str2):
'''
Args: two binary_string
Return: sum of the two binary strings in binary
'''
# sum of the two binary strings
total= []
max_len=max(len(str1), len(str2))
# fill the string with zeros to make the two strings same length
# turn the string to list and reverse it
list1=list(str1.zfill(max_len))
list1.reverse()
list2=list(str2.zfill(max_len))
list2.reverse()
carry=0
foriinrange(max_len):
# sum for this bit
bit_sum=int(list1[i])+int(list2[i]) +carry
total.append(str(bit_sum%2))
ifbit_sum>=2:
carry=1
ifcarry==1:
total.append('1')
total.reverse()
return''.join(total)