-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddBinary.py
51 lines (32 loc) · 1.02 KB
/
addBinary.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
'''
Given to binary numbers (in str format); add to get result in binary
'''
# Fastest 38ms
class Solution:
def addBinary(self, a: str, b: str) -> str:
anum, bnum = 0, 0
for i in range(len(a)):
anum += int(a[-i - 1]) * (2 ** i)
for i in range(len(b)):
bnum += int(b[-i - 1]) * (2 ** i)
cnum = anum + bnum
cstr = ""
if cnum <= 1: return str(cnum)
while cnum > 1:
cstr += str(cnum % 2)
cnum = cnum // 2
cstr += str(cnum)
return cstr[::-1]
class Solution2:
def addBinary(self, a: str, b: str) -> str:
anum, bnum = 0, 0
for i in range(len(a)):
anum += int(a[-i - 1]) * (2 ** i)
for i in range(len(b)):
bnum += int(b[-i - 1]) * (2 ** i)
return bin(anum+bnum).replace("0b", "")
class Solution3:
def addBinary(self, a: str, b: str) -> str:
anum = int(a, 2)
bnum = int(b, 2)
return bin(anum + bnum).replace("0b", "")