Bit Manipulation
Definition
Problems
1. Add binary
Intuition
Approach
Complexity
Time complexity:
Space complexity:
Code
- Dumb way to do it
class Solution:
def addBinary(self, a: str, b: str) -> str:
= min(len(a), len(b))
shorterLength = list(a)
a = list(b)
b = 0
remainder = []
result
for _ in range(shorterLength):
= a.pop(), b.pop()
num_a, num_b = eval(num_a + '+' + num_b) + remainder
interm = self.evaluate(interm, result, remainder)
remainder while a:
= a.pop()
num_a = int(num_a) + remainder
interm = self.evaluate(interm, result, remainder)
remainder while b:
= b.pop()
num_b = int(num_b) + remainder
interm = self.evaluate(interm, result, remainder)
remainder if remainder:
'1')
result.append(return ''.join(result[::-1])
def evaluate(self, interm, result, remainder):
if interm == 0:
'0')
result.append(= 0
remainder elif interm == 1:
'1')
result.append(= 0
remainder elif interm == 2:
'0')
result.append(= 1
remainder else:
'1')
result.append(return remainder
- Smart way to do it
class Solution:
def addBinary(self, a: str, b: str) -> str:
= ''
result = 0
remainder
= a[::-1], b[::-1]
a, b
for i in range(max(len(a), len(b))):
= int(a[i]) if i < len(a) else 0
digitA = int(b[i]) if i < len(b) else 0
digitB
= digitA + digitB + remainder
interm = str(interm % 2)
char = char + result
result = interm // 2
remainder
if remainder:
= '1' + result
result
return result