給定兩個二進位字元串,返回他們的和(用二進位表示)。 輸入為非空字元串且只包含數字 1 和 0。 示例 1: 輸入: a = "11", b = "1" 輸出: "100" 示例 2: 輸入: a = "1010", b = "1011" 輸出: "10101" class Solution: de ...
給定兩個二進位字元串,返回他們的和(用二進位表示)。
輸入為非空字元串且只包含數字 1
和 0
。
示例 1:
輸入: a = "11", b = "1" 輸出: "100"
示例 2:
輸入: a = "1010", b = "1011" 輸出: "10101"
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ a_len=len(a) b_len=len(b) result='' next ='0' while a_len and b_len : if sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 3: result +='1' next = '1' elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 2: result+='0' next ='1' elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) == 0: result+='0' next ='0' elif sum([int(next),int(a[a_len-1]),int(b[b_len-1])]) < 2: result+='1' next ='0' a_len-=1 b_len-=1 new = a[:a_len] if a_len > b_len else b[:b_len] if new: for i in new[::-1]: if sum([int(next),int(i)]) == 2: result+='0' next ='1' elif sum([int(next),int(i)]) == 1: result+='1' next ='0' else: result+='0' next ='0' if next != 0: result+=next return (result[::-1])
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return format(int(a,2)+int(b,2),"b")