-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_sum.py
More file actions
35 lines (27 loc) · 735 Bytes
/
binary_sum.py
File metadata and controls
35 lines (27 loc) · 735 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
#!/bin/python
import math
import os
import random
import re
import sys
def add_binary_nums(x,y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
# import pdb;pdb.set_trace()
result = ''
carry = 0
for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
print(add_binary_nums('11', '1'))
print(add_binary_nums('10', '10'))
print(add_binary_nums('111', '111'))
print(add_binary_nums('1111111', '1'))