-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.py
More file actions
61 lines (50 loc) · 1.23 KB
/
AddBinary.py
File metadata and controls
61 lines (50 loc) · 1.23 KB
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
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
aLen = len(a)
bLen = len(b)
if aLen > bLen:
b = "0"*(aLen - bLen) + b
elif aLen < bLen:
a = "0"*(bLen - aLen) + a
Len = len(a)
a = a[::-1]
b = b[::-1]
carry = 0
res = ""
for i in range(Len):
tmp = int(a[i])+int(b[i])+carry
res += str(tmp%2)
carry = tmp/2
if carry == 1:
res += "1"
return res[::-1]
s = Solution()
a = s.addBinary("1010","1011")
print a
class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
aDecimal = 0
bDecimal = 0
for i in range(len(a)):
aDecimal += int(a[i])*2**(len(a)-1-i)
print aDecimal
for i in range(len(b)):
bDecimal += int(b[i])*2**(len(a)-1-i)
#print aDecimal,bDecimal
sum = aDecimal + bDecimal
res = ""
if sum == 0:
return "0"
quotient = sum
while quotient != 0:
quotient = sum/2
mod = sum%2
res += str(mod)
sum = quotient
return res[::-1]