-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path0067-add-binary.py
More file actions
34 lines (24 loc) · 805 Bytes
/
0067-add-binary.py
File metadata and controls
34 lines (24 loc) · 805 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
# 67. Add Binary
# https://leetcode.com/problems/add-binary
class Solution:
def addBinary(self, a: str, b: str) -> str:
a_len, b_len = -len(a), -len(b)
i, carry,res = -1, 0, ""
while i >= a_len or i >= b_len:
a_bit = int(a[i]) if i >= a_len else 0
b_bit = int(b[i]) if i >= b_len else 0
sum = a_bit + b_bit + carry
res = str(sum % 2) + res
carry = sum // 2
i -= 1
return "1" + res if carry else res
# ********************#
# TEST #
# ********************#
import unittest
class TestStringMethods(unittest.TestCase):
def test_addBinary(self):
self.assertEqual(Solution.addBinary(self, "11", "1"), "100")
self.assertEqual(Solution.addBinary(self, "1010", "1011"), "10101")
if __name__ == '__main__':
unittest.main()