- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0067-add-binary.py
34 lines (24 loc) · 805 Bytes
/
0067-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
# 67. Add Binary
# https://leetcode.com/problems/add-binary
classSolution:
defaddBinary(self, a: str, b: str) ->str:
a_len, b_len=-len(a), -len(b)
i, carry,res=-1, 0, ""
whilei>=a_lenori>=b_len:
a_bit=int(a[i]) ifi>=a_lenelse0
b_bit=int(b[i]) ifi>=b_lenelse0
sum=a_bit+b_bit+carry
res=str(sum%2) +res
carry=sum//2
i-=1
return"1"+resifcarryelseres
# ********************#
# TEST #
# ********************#
importunittest
classTestStringMethods(unittest.TestCase):
deftest_addBinary(self):
self.assertEqual(Solution.addBinary(self, "11", "1"), "100")
self.assertEqual(Solution.addBinary(self, "1010", "1011"), "10101")
if__name__=='__main__':
unittest.main()