Add Two Binary
Question
Given two binary strings, return their sum (also a binary string).
Example
a = 11
b = 1
Return 100
Thoughts
没什么可说的,加个carry一个一个算过去
注意点
- 最后的carry如果是1也要加上去
Solution
class Solution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
def addBinary(self, a, b):
# Write your code here
result = ""
index1 = len(a) - 1
index2 = len(b) - 1
carry = 0
while index1 >= 0 and index2 >= 0:
curSum = int(a[index1]) + int(b[index2]) + carry
if curSum < 2:
carry = 0
result = str(curSum) + result
elif curSum == 2:
carry = 1
result = "0" + result
elif curSum == 3:
carry = 1
result = "1" + result
index1 -= 1
index2 -= 1
while index1 >= 0:
curSum = int(a[index1]) + carry
if curSum < 2:
carry = 0
result = str(curSum) + result
else:
carry = 1
result = "0" + result
index1 -= 1
while index2 >= 0:
curSum = int(b[index2]) + carry
if curSum < 2:
carry = 0
result = str(curSum) + result
else:
carry = 1
result = "0" + result
index2 -= 1
if carry == 1:
result = str(carry) + result
return result