-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_AddBinary.py
More file actions
25 lines (18 loc) · 756 Bytes
/
01_AddBinary.py
File metadata and controls
25 lines (18 loc) · 756 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
# Question link - https://leetcode.com/problems/add-binary/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = "" # Result string
carry = 0 #The number bits should be carry
# Reverse the string
a , b = a[::-1] , b[::-1]
for i in range(max(len(a) , len(b))):
digitA = ord(a[i]) - ord("0") if i < len(a) else 0
digitB = ord(b[i]) - ord("0") if i < len(b) else 0
total = digitA + digitB + carry
# For binary we need to mod 2
char = str(total % 2)
res = char + res
carry = total // 2
if carry:
res = "1" + res
return res