Add Binary [leetcode easy]

Leetcode67

Example,

Input: a = “11”, b = “1”
Output: “100”

Solution 0: Using built-in function, haha

1
2
def addBinary(self, a: str, b: str) -> str:
return bin(int(a,2) + int(b,2))[2:] # bin starts with '0b'

Solution 1: Sum the number from the back of both strings, update carry over value if the sum is greater than 1, after the while loop do another check if carry over value is 1 to add the last carry over value

time complexiity: O(max(n,m))
space complexity: O(max(n,m))
runtime: 36 ms | faster than 33.66% submissions
memory: 12.7 MB

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
def addBinary(self, a: str, b: str) -> str:
result = ''

i = len(a) - 1
j = len(b) - 1
carry = 0

while i >= 0 or j >= 0:
left = int(a[i]) if i >= 0 else 0
right = int(b[j]) if j >= 0 else 0

total = left + right + carry

if total == 3:
total = 1
carry = 1
elif total == 2:
total = 0
carry = 1
else:
carry = 0

result = str(total) + result

if i > 0:
i -= 1
if j > 0:
j -= 1

if carry == 1:
result = str(carry) + result

return result

Another day,

another question.