題目:
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
思路:
二進制加法思想就是:從最低位兩位數相加,到2後進一位加到最高項。這就是代碼的整體思路。
代碼:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
aIndex,bIndex,flag,s = len(a)-1,len(b)-1,0,''
while aIndex >= 0 and bIndex >= 0:
num = int(a[aIndex])+int(b[bIndex])+flag
flag = num/2
num %= 2
s = str(num)+s
aIndex -= 1
bIndex -= 1
while aIndex >= 0:
num = int(a[aIndex])+flag
flag = num/2
num %= 2
s = str(num)+s
aIndex -= 1
while bIndex >= 0:
num = int(b[bIndex])+flag
flag = num/2
num %= 2
s = str(num)+s
bIndex -= 1
if flag == 1:
s = '1'+ s
return s